Set item quantity to multiples of “x” for products in a specific category in Woocommerce

后端 未结 1 1374
情歌与酒
情歌与酒 2020-12-21 15:43

I found online a snippet that allows you to set in the cart a minimum purchase to multiple quantities of “6”.

Here it is:

add_action( ‘woocommerce_ch         


        
相关标签:
1条回答
  • 2020-12-21 15:58

    Update (extended to parent product categories too)

    Try the following that will make your code work only for a specific product category:

    // Custom conditional function that checks also for parent product categories
    function has_product_category( $product_id, $category_ids ) {
        $term_ids = array(); // Initializing
    
        // Loop through the current product category terms to get only parent main category term
        foreach( get_the_terms( $product_id, 'product_cat' ) as $term ){
            if( $term->parent > 0 ){
                $term_ids[] = $term->parent; // Set the parent product category
                $term_ids[] = $term->term_id;
            } else {
                $term_ids[] = $term->term_id;
            }
        }
        return array_intersect( $category_ids, array_unique($term_ids) );
    }
    
    
    add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
    function woocommerce_check_cart_quantities() {
        $multiples = 6;
        $total_products = 0;
        $category_ids = array( 35 );
        $found = false;
    
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( has_product_category( $cart_item['product_id'], $category_ids ) ) {
                $total_products += $cart_item['quantity'];
                $found = true;
            }
        }
        if ( ( $total_products % $multiples ) > 0 && $found )
            wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
    }
    

    Code goes in function.php file of your active child theme (active theme). Tested and works.

    0 讨论(0)
提交回复
热议问题