如何仅在WooCommerce product_category短代码中显示商品短描述
解决方法
要实现仅在[product_category excerpt="yes"]短代码中显示商品短描述,需修改原有函数并添加参数传递逻辑,具体操作如下:
1. 修改短描述输出函数,添加条件判断
将原来的全局输出逻辑改为仅满足指定条件时才输出:
add_action( 'woocommerce_after_shop_loop_item_title', 'output_product_excerpt', 35 ); function output_product_excerpt() { global $wp_query, $post; // 检查当前循环是否来自product_category短代码,且excerpt参数为yes $excerpt_enabled = isset( $wp_query->query_vars['excerpt'] ) ? $wp_query->query_vars['excerpt'] : 'no'; // 仅当参数为yes且短描述不为空时输出,用wpautop保留格式 if ( $excerpt_enabled === 'yes' && !empty( $post->post_excerpt ) ) { echo wpautop( $post->post_excerpt ); } }
2. 传递短代码的excerpt参数到查询变量
通过过滤器把product_category短代码中的excerpt参数传递给查询,让输出函数能识别该条件:
add_filter( 'woocommerce_shortcode_products_query', 'pass_excerpt_param_to_query', 10, 3 ); function pass_excerpt_param_to_query( $query_args, $atts, $loop_name ) { // 仅处理product_category短代码的参数 if ( $loop_name === 'product_category' && isset( $atts['excerpt'] ) ) { $query_args['excerpt'] = sanitize_text_field( $atts['excerpt'] ); } return $query_args; }
使用方式
- 需要显示短描述时,调用带参数的短代码:
[product_category category="你的分类别名" excerpt="yes"] - 不需要显示时,使用默认短代码即可:
[product_category category="你的分类别名"]
修改完成后,关联商品、追加销售等其他商品循环不会触发短描述输出,完全实现按需显示的需求。
内容的提问来源于stack exchange,提问作者Ryan Cole
相关产品推荐
相关产品推荐

