firza faisal
firza faisal

Reputation: 11

Hide WooCommerce coupon field for specific products?

I am trying to hide the coupon field for some products from WooCommerce cart and checkout pages. After some search in google, I found some codes to hide coupon field but just for 1 product.

How can I handle multiple products within this code:

// hide coupon field on the checkout page
function disable_coupon_field_on_checkout( $enabled ) {
    if ( is_checkout() ) {
 
        $product_id = 240790;
        $in_cart = false;
        
        foreach( WC()->cart->get_cart() as $cart_item ) {
           $product_in_cart = $cart_item['product_id'];
 
           if ( $product_in_cart === $product_id ) $in_cart = true;
        }
 
        if ( $in_cart === true )
        {
            $enabled = false;
        }
    }
    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'disable_coupon_field_on_checkout' );
 
// hide coupon field on the cart page
function disable_coupon_field_on_cart( $enabled ) {
    if ( is_cart() ) {
        $product_id = 240790;
        $in_cart = false;
        
        foreach( WC()->cart->get_cart() as $cart_item ) {
           $product_in_cart = $cart_item['product_id'];
 
           if ( $product_in_cart === $product_id ) $in_cart = true;
        }
 
        if ( $in_cart === true )
        {
            $enabled = false;
        }
    }
    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'disable_coupon_field_on_cart' );

Any help is appreciated.

Upvotes: 0

Views: 164

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253824

The following code will handle multiple product IDs and/or variation IDs too, for cart and checkout pages, disabling the coupon field for those products:

// hide coupon field on cart and checkout pages
add_filter( 'woocommerce_coupons_enabled', 'disable_coupon_field_for_specific_products' );
function disable_coupon_field_for_specific_products( $enabled ) {
    if ( ( is_checkout() && !is_wc_endpoint_url() ) || is_cart() ) {
        // here define your product IDs in the array
        $product_ids = array(240790, 240792, 240795, 240798);
        
        // Loop through cart items
        foreach( WC()->cart->get_cart() as $item ) {
            if ( count( array_intersect( [$item['product_id'], $item['variation_id']], $product_ids ) ) > 0 ) {
                return false;
            }
        }
    }
    return $enabled;
}

It should work.

Upvotes: 0

Related Questions