如何修改WooCommerce可变订阅产品全额付款的价格文本
解决WooCommerce可变订阅产品全额付款选项价格文本修改问题
问题描述
我有一款可分12个月分期支付的WooCommerce可变订阅产品,当“分期数”选择“全额付款”(对应1个月订阅周期)时,需要修改默认显示的“£xxx for 1 month”文本,其余2-12个月的分期选项保持原有显示格式。
尝试过的无效方案
全局修改代码(不符合需求)
这段代码会全局移除所有订阅产品的周期文本,无法仅针对全额付款选项调整:
add_filter('woocommerce_subscriptions_product_price_string_inclusions', 'remove_subscription_inclusions', 10, 2); function remove_subscription_inclusions( $include, $product ) { $include['subscription_length'] = ''; $include['subscription_period'] = ''; return $include; }
无效的变体遍历代码
以下代码尝试遍历所有变体但未生效,原因是钩子上下文无法直接获取当前选中的变体:
add_filter('woocommerce_subscriptions_product_price_string_inclusions', 'custom_subscription_price_string_inclusions', 10, 2); function custom_subscription_price_string_inclusions( $include, $product ) { if ($product->is_type('subscription')) { $variations = $product->get_available_variations(); foreach ($variations as $variation) { $subscription_length = isset($variation['attributes']['pa_subscription_length']) ? $variation['attributes']['pa_subscription_length'] : ''; $subscription_period = isset($variation['attributes']['pa_subscription_period']) ? $variation['attributes']['pa_subscription_period'] : ''; if ('1' === $subscription_length && 'month' === $subscription_period) { $include['price_string'] = '£' . $variation['display_price'] . ' (Full payment for 1 month)'; $include['subscription_length'] = ''; $include['subscription_period'] = ''; } } } return $include; }
有效解决方案
使用woocommerce_subscription_price_string钩子,针对当前选中的变体属性进行文本替换:
add_filter('woocommerce_subscription_price_string', 'custom_single_payment_subscription_price_text', 20, 3); function custom_single_payment_subscription_price_text( $price_string, $product, $args ) { // 仅处理可变订阅产品 if ( ! $product->is_type('variable-subscription') ) { return $price_string; } // 获取当前选中的分期长度属性值 $selected_length = ''; // 前端选择变体时获取POST参数 if ( isset( $_POST['attribute_pa_subscription_length'] ) ) { $selected_length = sanitize_text_field( $_POST['attribute_pa_subscription_length'] ); } else { // 页面加载时获取默认选中的属性 $default_attrs = $product->get_default_attributes(); $selected_length = isset( $default_attrs['pa_subscription_length'] ) ? $default_attrs['pa_subscription_length'] : ''; } // 匹配1个月的全额付款选项,替换文本 if ( '1' === $selected_length ) { // 方式1:替换原有文本中的"for 1 month" return str_replace( 'for 1 month', '(全额付款)', $price_string ); // 方式2:直接生成自定义价格文本(如果需要完全自定义格式) // $price = wc_price( $product->get_price() ); // return $price . ' (全额付款)'; } // 其他分期选项保持原文本 return $price_string; }
注意事项
- 确保代码中的属性slug
pa_subscription_length与你产品中“分期数”属性的实际slug一致(可在WooCommerce后台的属性设置中查看)。 - 可根据需求选择文本替换方式:方式1保留原有价格格式仅替换周期文本;方式2完全自定义价格显示格式。
- 将代码添加到主题的
functions.php文件或自定义插件中。
内容的提问来源于stack exchange,提问作者OverdueOrange
相关产品推荐
相关产品推荐

