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

WooCommerce+WP6.1:如何在加入购物车按钮内显示变体产品价格?

将WooCommerce变量产品价格嵌入加入购物车按钮的解决方案

1. 隐藏默认变体价格区域

首先通过CSS隐藏原本在下拉框下方显示的变体价格:

/* 隐藏默认的变体价格展示 */
.single-product div.product .woocommerce-variation-price {
    display: none !important;
}

将这段代码添加到主题的自定义CSS区域,或者子主题的style.css文件中。

2. 动态更新加入购物车按钮的价格

通过JavaScript监听变体选择事件,把选中的变体价格插入到加入购物车按钮内:

方法一:直接添加到主题自定义JS

jQuery(document).ready(function($) {
    // 监听变体选择事件
    $('.variations_form').on('found_variation', function(event, variation) {
        // 定位加入购物车按钮
        const addToCartBtn = $(this).find('.single_add_to_cart_button');
        // 更新按钮文本,拼接价格
        addToCartBtn.html(`加入购物车 - ${variation.display_price_html}`);
    });

    // 变体重置时恢复默认按钮文本
    $('.variations_form').on('reset_data', function() {
        const addToCartBtn = $(this).find('.single_add_to_cart_button');
        addToCartBtn.text('加入购物车');
    });
});

方法二:通过主题functions.php添加脚本

如果更习惯通过PHP嵌入脚本,可将以下代码添加到主题(或子主题)的functions.php文件中:

function embed_price_in_add_to_cart_btn() {
    // 仅在变量产品页面加载脚本
    if (is_product() && wc_get_product()->is_type('variable')) {
        wp_add_inline_script('jquery', '
            jQuery(document).ready(function($) {
                $(".variations_form").on("found_variation", function(event, variation) {
                    const addToCartBtn = $(this).find(".single_add_to_cart_button");
                    addToCartBtn.html("加入购物车 - " + variation.display_price_html);
                });

                $(".variations_form").on("reset_data", function() {
                    const addToCartBtn = $(this).find(".single_add_to_cart_button");
                    addToCartBtn.text("加入购物车");
                });
            });
        ');
    }
}
add_action('wp_enqueue_scripts', 'embed_price_in_add_to_cart_btn');

注意事项

  • 如果你的主题自定义了加入购物车按钮的类名,需要把代码中的.single_add_to_cart_button替换为主题实际使用的按钮选择器。
  • 若使用缓存插件,修改后需要清空缓存才能看到效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:05:31