如何在脚本中指定特定WooCommerce产品?自定义订阅价格字符串异常
自定义WooCommerce特定订阅产品的价格字符串
问题背景
现有一段自定义WooCommerce订阅价格字符串的代码可正常运行,但会修改网站所有订阅产品,需求是仅对单个或多个特定产品应用该自定义逻辑,不影响其他订阅产品。
原始生效但影响所有产品的代码
add_filter( 'woocommerce_subscriptions_product_price_string', 'my_subs_price_string1', 10, 3 ); function my_subs_price_string1( $subscription_string, $product, $include ) { /**** var_dump($product); Various variables are available to us ****/ return 'Today ' . wc_price( $product->subscription_sign_up_fee ) . ', a ' . $product->subscription_trial_length . ' ' . $product->subscription_trial_period . ' trial of the product, then an outright purchase of ' . wc_price( $product->subscription_price ); }
尝试过但不符合需求的代码
尝试过参考代码片段,但该代码仅做特定字符串替换,无法实现自定义价格字符串的预期效果:
function wc_subscriptions_custom_price_string( $pricestring ) { global $product; $products_to_change = array( 2212 ); if ( in_array( $product->id, $products_to_change ) ) { $newprice = str_replace( 'on the 20th day of every 6th month', 'on the 20th November and 20th May', $pricestring ); } return $newprice; } add_filter( 'woocommerce_subscriptions_product_price_string', 'wc_subscriptions_custom_price_string' ); add_filter( 'woocommerce_subscription_price_string', 'wc_subscriptions_custom_price_string' );
解决方案:仅对指定产品应用自定义价格字符串
修改原始代码,加入产品ID判断逻辑,仅目标产品执行自定义字符串生成,其他产品返回默认字符串:
add_filter( 'woocommerce_subscriptions_product_price_string', 'my_subs_price_string1', 10, 3 ); function my_subs_price_string1( $subscription_string, $product, $include ) { // 定义需要修改的目标产品ID,可添加多个ID到数组中 $target_product_ids = array( 2212, 3456 ); // 获取当前产品ID,兼容WooCommerce新旧版本 $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id; // 如果当前产品不在目标数组中,直接返回原价格字符串 if ( !in_array( $product_id, $target_product_ids ) ) { return $subscription_string; } // 仅对目标产品执行自定义价格字符串逻辑 return 'Today ' . wc_price( $product->subscription_sign_up_fee ) . ', a ' . $product->subscription_trial_length . ' ' . $product->subscription_trial_period . ' trial of the product, then an outright purchase of ' . wc_price( $product->subscription_price ); }
关键说明
$target_product_ids:替换为你需要修改的产品ID,多个ID用英文逗号分隔- 兼容WooCommerce新旧版本的产品ID获取方式:
get_id()是新版本方法,$product->id兼容旧版本 - 非目标产品直接返回原字符串,不影响默认显示
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

