Jump to content

Force coupon for certain product in Woocommerce


ChuckSA

Recommended Posts

I'm trying to force the user to apply a coupon for one specific product/category only.

I found the following codeĀ  but am having endless trouble getting it to run. I suspect it's old code and am unsure what to change. It's supposed to go in the functions file, so I've been using the Code Snippets plugin to run it

// Force Coupon codes for Woocommerce
add_action('woocommerce_check_cart_items', 'mandatory_coupon_code');
function mandatory_coupon_code()
{
        // set Here your categories IDs, slugs or names
        $categories = array(18,19,87);
        $found = false;

        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) 
            if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
                // Product category found in cart items
                $found = true;
                // Exit from loop
                break;
            }
        }
        $coupons = WC()->cart->get_applied_coupons();

        // The Notice is displayed for that product categories when no mandatory coupon has been entered
        if( count( $coupons ) > 0 && $found )
            wc_add_notice( __( 'A coupon code is mandatory for this product.', 'woocommerce' ), 'error' );

I will truly appreciate any help I can get here.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.