You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Woocommerce 如何在产品标题后仅展示用户选中的单个属性值

代码修改方案

原代码的问题在于使用get_attribute()方法会直接输出商品全部已分配的属性值,且为服务端固定渲染,无法跟随用户前端选择的变体动态更新。你可以使用下方代码直接替换原有代码即可实现需求:

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_single_product_summary', 'custom_template_single_title', 5 );
function custom_template_single_title() {
    global $product;
    // 输出基础标题,预留动态修改标识
    echo '<h1 class="product_title entry-title" data-base-title="'.esc_html(get_the_title()).'">';
    the_title();
    echo '</h1>';

    // 仅可变体商品加载动态逻辑
    if ($product->is_type('variable')) {
        wc_enqueue_js("
            // 监听变体选中事件
            jQuery(document).on('found_variation', 'form.variations_form', function(event, variation) {
                const baseTitle = jQuery('.product_title.entry-title').data('base-title');
                // 此处将pa_color替换为你实际使用的属性slug
                const selectedVal = variation.attributes['attribute_pa_color'];
                if (selectedVal) {
                    const attrText = jQuery('.variations select#pa_color option[value=\"'+selectedVal+'\"]').text().trim();
                    jQuery('.product_title.entry-title').text(baseTitle + ' - ' + attrText);
                } else {
                    jQuery('.product_title.entry-title').text(baseTitle);
                }
            });
            // 监听变体重置事件,恢复原始标题
            jQuery(document).on('reset_data', 'form.variations_form', function() {
                const baseTitle = jQuery('.product_title.entry-title').data('base-title');
                jQuery('.product_title.entry-title').text(baseTitle);
            });
        ");
    }
}

配置说明

  • 代码中的pa_color为示例属性的slug,你需要替换为自己要展示的属性实际slug,如果是你之前使用的brand-name属性,直接对应替换即可
  • 全局属性默认会带pa_前缀,自定义属性无此前缀,填写时注意和后台属性编辑页的slug保持一致

内容的提问来源于stack exchange,提问作者Uxell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:54:05