WooCommerce商店页如何调用展示单个产品变体的存储描述
问题根源
默认的woocommerce_template_single_excerpt函数仅会读取全局主产品对象的摘要内容,无法自动识别WPC Show Single Variations插件渲染的独立变体对象,因此执行后只会返回父级可变产品的属性标题或父产品摘要,无法调取变体自身存储的描述。WooCommerce变体的独立描述存储在变体对象的description字段中,需要单独判断当前循环项类型后再读取输出。
实现代码
移除你之前添加的挂载原生摘要函数的代码,将以下代码添加到当前子主题的functions.php文件,或自定义代码片段插件中执行即可:
add_action( 'woocommerce_after_shop_loop_item_title', 'output_variation_single_excerpt', 20 ); function output_variation_single_excerpt() { global $product; // 判断当前循环项是否为产品变体 if ( $product->is_type( 'variation' ) ) { // 读取变体自身存储的描述内容 $excerpt = $product->get_description(); // 变体未填写独立描述时,fallback到父产品短描述,不需要可删除该段 if ( empty( $excerpt ) ) { $parent = wc_get_product( $product->get_parent_id() ); $excerpt = $parent ? $parent->get_short_description() : ''; } // 按WooCommerce默认样式输出描述 if ( $excerpt ) { echo '<div class="woocommerce-product-details__short-description variation-custom-excerpt">' . wp_kses_post( $excerpt ) . '</div>'; } } else { // 普通商品走原生摘要输出逻辑 woocommerce_template_single_excerpt(); } }
调整说明
- 如果需要控制描述展示字数,可以在输出前用
wp_trim_words( $excerpt, 15 )截断内容,第二个参数为需要展示的字数 - 如果你的变体描述存储在自定义字段中,将
$product->get_description()替换为$product->get_meta( '你的自定义字段key' )即可 - 如果代码添加后仍不显示内容,检查WPC Show Single Variations插件设置,确认已开启循环页替换产品对象为变体实例的相关选项,避免全局
$product未正确加载变体数据
内容的提问来源于stack exchange,提问作者hemoglobin
相关产品推荐
相关产品推荐

