Allow add to cart 3 products max for a specific product category in Woocommerce

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-10 06:41:36

问题


I am trying to send out a maximum of 3 free samples to customers with free shipping.

I have created some 0 priced product and set them in "samples" product category.

This specific products have option "sold individually" so customers can only have one of each sample.

I cannot figure out how to allow only a maximum of 3 samples products from this product category on cart.

Any help is appreciated.


回答1:


This can be done easily using woocommerce_add_to_cart_validation action hook to limit customers to a maximum of 3 items from "sample" product category, this way:

add_action('woocommerce_add_to_cart_validation', 'max_3_items_for_samples', 20, 3 );
function max_3_items_for_samples( $passed, $product_id, $quantity ) {
    // HERE define your product category ID, slug or name.
    $category = 'clothing';
    $limit = 3; // HERE set your limit
    $count = 0;

    // Loop through cart items checking for specific product categories
    foreach ( WC()->cart->get_cart() as $cat_item ) {
        if( has_term( $category, 'product_cat', $cat_item['product_id'] ) )
            $count++;
    }
    if( has_term( $category, 'product_cat', $product_id ) && $count == $limit )
        $count++;

    // Total item count for the defined product category is more than 3
    if( $count > $limit ){
        // HERE set the text for the custom notice
        $notice = __('Sorry, you can not add to cart more than 3 free samples.', 'woocommerce');
        // Display a custom notice
        wc_add_notice( $notice, 'error' );
        // Avoid adding to cart
        $passed = false;
    }

    return $passed;
}

Code goes in function.php file of your active child theme (or theme).

Tested and works.




回答2:


The above solution does not work. 1) It allows you to initially add more than the limit the first time the product is added. I believe this is because the validation comes before the items are added to the cart, yet the function above loops through items that are already in the cart and 2) it lets the user enter as many of a product that they want, on the the /cart/ page because the woocommerce_update_cart_validation filter is not used.



来源:https://stackoverflow.com/questions/49015289/allow-add-to-cart-3-products-max-for-a-specific-product-category-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!