Search code examples
phpwordpresswoocommercecustom-taxonomycoupon

Hide cart coupon field for specific products category in Woocommerce 3


function hidding_coupon_field_on_cart_for_a_category($enabled) {
    // Set your special category name, slug or ID here:
    $special_cat = 'clothing';
    $bool = false;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $wc_product = $cart_item['data'];
        // Woocommerce compatibility
        $product_id = method_exists( $wc_product, 'get_id' ) ? $wc_product->get_id() : $wc_product->id;
        if ( has_term( $special_cat, 'product_cat', $product_id ) )
            $bool = true;
    }

    if ( $bool && is_cart() ) {
        $enabled = false;
    }
    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'hidding_coupon_field_on_cart_for_a_category' );

Found this snippet and this works great but if i have a variable instead of a simple product, it seems that the category hiding doesn't work anymore.

$special_cat = 'prints';
$product_id  = array('9461', '9597');

Also to exclude the main product id and the variations id doesn't work. Anyone have an idea?


Solution

  • Update 2 - October 2018 (still perfectly work on last Woocommerce version)

    To make it work for all product types including variable products use this instead:

    add_filter( 'woocommerce_coupons_enabled', 'product_category_hide_cart_coupon_field', 20, 1 );
    function product_category_hide_cart_coupon_field( $enabled ) {
        // Only on frontend
        if( is_admin() ) 
           return $enabled;
    
        // Set your special categories names, slugs or IDs here in the array:
        $categories = array('prints');
        $found = false; // Initializing
    
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
                $found = true;
                break; // We stop the loop
            }
        }
    
        if ( $found && is_cart() ) {
            $enabled = false;
        }
        return $enabled;
    }
    

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