簡體   English   中英

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 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM