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

实现WooCommerce单品加入购物车按钮文本随购物车状态切换

WooCommerce 移除购物车商品后恢复「加入购物车」按钮文本

你的现有PHP代码已经实现了页面加载时根据商品是否在购物车修改按钮文本,但WooCommerce移除商品默认是AJAX操作,不会刷新页面,所以需要配合JavaScript监听移除事件,即时恢复按钮文本。

步骤1:保留原有PHP代码

这段代码负责页面初始加载时的按钮文本判断:

add_filter( 'woocommerce_product_single_add_to_cart_text', 'already_in_cart_single_product' );
function already_in_cart_single_product( $label ) {
   foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
      $product = $values['data'];
      if( get_the_ID() == $product->get_id() ) {
         $label = __('Product already in Cart. Add again?', 'woocommerce');
      }
   } 
   return $label;
}

步骤2:添加JavaScript实现即时恢复

添加以下代码到主题的functions.php中,它会监听购物车商品移除的AJAX事件,当当前页面的商品被移除时,立即恢复按钮文本:

add_action('wp_footer', 'restore_add_to_cart_button_text_after_remove');
function restore_add_to_cart_button_text_after_remove() {
    // 仅在单个商品页面加载脚本
    if (is_product()) {
    ?>
    <script>
    jQuery(document).ready(function($) {
        // 监听WooCommerce的商品移除事件
        $(document).on('removed_from_cart', function(event, fragments, cart_hash, removed_product_id) {
            // 获取当前页面的商品ID
            var current_product_id = $('input[name="add-to-cart"]').val();
            
            // 如果移除的是当前页面的商品,恢复按钮文本
            if (current_product_id == removed_product_id) {
                $('.single_add_to_cart_button').html('<?php echo esc_js(__("Add to cart", "woocommerce")); ?>');
            }
        });
    });
    </script>
    <?php
    }
}

补充说明

  • 若需同时处理产品列表页面的按钮,可调整JS中的选择器(比如.add_to_cart_button)和商品ID获取逻辑
  • 代码中的"Add to cart"可替换为你需要的默认按钮文本,保持与WooCommerce翻译体系一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:42:45