How to hide WooCommerce's coupon field for a specific product?
P粉138871485
P粉138871485 2023-07-28 11:22:20
0
1
405
<p>I'm trying to hide the coupon fields for certain products in WooCommerce cart and checkout page. After searching on Google, I found some code that hides the coupon field, but only for one product. </p><p>How can I handle multiple products in this code: </p><p><br /></p> <pre class="brush:php;toolbar:false;">// 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' );</pre>
P粉138871485
P粉138871485

reply all(1)
P粉615829742

The code below will handle multiple product IDs and/or variant IDs for use in the shopping cart and checkout pages, disabling the coupon field for these 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;
}

Should be useful

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!