WooCommerce:当产品已经在购物车中时更改添加到购物车的文本

WooCommerce: change the add to cart text when the product is already in cart

我在更改 WooCommerce/WordPress 中 “添加到购物车” 按钮的文本时遇到问题。

目前下面的代码,我想要它,这样如果产品已经在购物车中,“添加到购物车” 按钮通过更改文本来表明它已经反映出来在购物车中。

目前,即使产品在购物车中,它仍然是“添加到购物车”。奇怪的是,如果我删除 if 条件,文本会发生变化,所以我假设 if 条件有问题,但我看不出有任何问题。

add_filter('woocommerce_product_add_to_cart_text', 'woocommerce_custom_add_to_cart_text');
function woocommerce_custom_add_to_cart_text($add_to_cart_text, $product_id) {
    global $woocommerce;
    
    foreach($woocommerce->cart->get_cart() as $key => $val ) {
        $_product = $val['data'];
 
        if($product_id == $_product->id ) {
            $add_to_cart_text = 'Already in cart';
        }
        
    return $add_to_cart_text;
    }
}
  • $_product->id 应该是 $_product->get_id()
  • 在 foreach 循环外使用 return
  • 全局 $woocommerce 没有必要
  • 来自 woocommerce_product_add_to_cart_text 过滤器挂钩的第二个参数是 $product,而不是 $product_id

所以你得到

function woocommerce_custom_add_to_cart_text( $add_to_cart_text, $product ) {
    // Get cart
    $cart = WC()->cart;
    
    // If cart is NOT empty
    if ( ! $cart->is_empty() ) {

        // Iterating though each cart items
        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
            // Get product id in cart
            $_product_id = $cart_item['product_id'];
     
            // Compare 
            if ( $product->get_id() == $_product_id ) {
                // Change text
                $add_to_cart_text = __( 'Already in cart', 'woocommerce' );
                break;
            }
        }
    }

    return $add_to_cart_text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_add_to_cart_text', 10, 2 );