如何在WooCommerce指定分类商品的短描述下方添加自定义文本
问题根源
原来的条件判断逻辑完全写反了,当前代码的return触发条件是「商品没有短描述 且 属于3d-pop-up-cards分类」,其余所有场景(包括Phone Covers分类的所有商品、3d-pop-up-cards分类下有短描述的商品)都会继续执行后续代码,把自定义文本拼接到短描述后面,所以才会出现两个分类都显示自定义文本的问题。
额外补充兼容优化点:WooCommerce 3.0+ 版本之后不推荐直接访问$product->id属性,建议用$product->get_id()方法获取商品ID,避免版本兼容报错。
修正后的完整代码
add_action( 'woocommerce_single_product_summary', 'custom_single_product_summary', 2 ); function custom_single_product_summary(){ global $product; remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 ); add_action( 'woocommerce_single_product_summary', 'custom_single_excerpt', 20 ); } function custom_single_excerpt(){ global $post, $product; $short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt ); // 非3d pop up cards分类的商品直接输出原有短描述,不追加自定义内容 if ( !has_term( '3d-pop-up-cards', 'product_cat', $product->get_id() ) ) { echo '<div class="woocommerce-product-details__short-description">'.$short_description.'</div>'; return; } // 自定义文本 $custom_text = '<ul class="fancy-bullet-points red"> <strong><span style="color: #ff0000;"><li>My Text Here</li></span></strong> </ul>'; ?> <div class="woocommerce-product-details__short-description"> <?php echo $short_description . $custom_text; // WPCS: XSS ok. ?> </div> <?php }
如果你需要同时保留「3d pop up cards分类下的商品没有短描述时不输出任何内容」的原有逻辑,可以把上述代码中的分类判断替换为:
if ( !has_term( '3d-pop-up-cards', 'product_cat', $product->get_id() ) || !$short_description ) { if($short_description){ echo '<div class="woocommerce-product-details__short-description">'.$short_description.'</div>'; } return; }
内容的提问来源于stack exchange,提问作者Nguyen Minh
相关产品推荐
相关产品推荐

