Dudikowski Dudikowski - 1 year ago 67
PHP Question

Hiding coupon field in cart for a product category

I'm trying to hide out the coupon code field in the cart for a few excluded products. I've added a product category and exclude this category from the coupon use.

A snippet restricts the cart so only one product at a time is allowed. It's unnecessary to show the coupon code for excluded products in this case. The validation would not let the user apply the coupon but it would be even better if they didn't even see the coupon fields.

This is a snippet I found that finds a product category and displays a message:

// Find product category
add_action( 'woocommerce_check_cart_items', 'checking_cart_items', 12 );
function checking_cart_items() {
// set your special category name, slug or ID here:
$special_cat = 'myproductcategory';
$bool = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$item = $cart_item['data'];
if ( has_term( $special_cat, 'product_cat', $item->id ) )
$bool = true;
}
// Displays a message if category is found
if ($bool)
echo '<div class="checkoutdisc">A custom message displayed.</div>';

}


This is the general snippet that hides the coupon code in the cart:

// hide coupon field on cart page
function hide_coupon_field_on_cart( $enabled ) {

if ( is_cart() ) {
$enabled = false;
}

return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_on_cart' );


How can I make these functions work together?

Thanks

Answer Source

Update: Compatibility with WooComerce 3+

Yes it's possible, using this combination of code:

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' );

Naturally, this goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.


References:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download