簡體   English   中英

購物車中每個產品類別只允許一個產品

[英]Allow only one product per product category in cart

在這個問題/答案中,我找到了有關如何僅在Woocommerce的購物車中為每個類別添加一個產品的PHP代碼。

該代碼可以正常工作,但是我想將最新添加的產品添加到購物車中,如果購物車中已經有該類別的產品,則希望刪除最舊的產品。

add_filter( 'woocommerce_add_to_cart_validation', 'custom_checking_product_added_to_cart', 10, 3 );
function custom_checking_product_added_to_cart( $passed, $product_id, $quantity) {

// HERE Type your alert displayed message
// $message = __( 'BLA BLA YOUR MESSAGE.', 'woocommerce' );

$product_cats_object = get_the_terms( $product_id, 'product_cat' );
foreach($product_cats_object as $obj_prod_cat){
    $product_cats[] = $obj_prod_cat->slug;
}

foreach (WC()->cart->get_cart() as $cart_item ){
if( has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) {
        $passed = false;
        wc_add_notice( $message, 'error' );
        break;
    }
}
return $passed;
}

這是來自LoicTheAztec的一段代碼。 它工作正常,但我需要一個額外的選擇...

在我的Woocommerce中,有5個不同的類別,每個類別中只有一個放置在購物車中。 最新添加的項目應保留,必須從購物車中刪除購物車中已經存在的相同類別的項目。 你們中的某人有解決方案嗎?

非常感謝!

這是您的安全代碼,它將刪除商品類別與當前商品類別匹配的購物車商品。

add_filter( 'woocommerce_add_to_cart_validation', 'custom_checking_product_added_to_cart', 10, 3 );
function custom_checking_product_added_to_cart( $passed, $product_id, $quantity) {

    // Getting the product categories slugs in an array for the current product
    $product_cats_object = get_the_terms( $product_id, 'product_cat' );
    foreach($product_cats_object as $obj_prod_cat)
        $product_cats[] = $obj_prod_cat->slug;

    // Iterating through each cart item
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ){

        // When the product category of the current product match with a cart item
        if( has_term( $product_cats, 'product_cat', $cart_item['product_id'] ))
        {
            // Removing the cart item
            WC()->cart->remove_cart_item($cart_item_key);

            // Displaying a message
            wc_add_notice( 'Only one product from a category is allowed in cart', 'notice' );

            // We stop the loop
            break;
        }
    }
    return $passed;
}

這段代碼會出現在您活動的子主題(或主題)的function.php文件中,也可能會出現在任何插件文件中。

此代碼已經過測試,可用於WooCommerce 2.6+和3.0+版本

暫無
暫無

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

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