Pixeljack
Pixeljack

Reputation: 25

Hide Coupons Based on Products in Basket

I'm trying to develop a small piece of code that builds upon the WooCommerce Subscription & All Products for WooCommerce Subscriptions plugins that hide/shows the coupon option at Checkout depending on whether the customer has chosen a subscription or one-time purchase.

From reading online I've managed to create code that hides the coupon box for all checkout users, but it lacks the functionality of checking whether the basket is a subscription or not.

Here's the code so far:

function hide_coupon_field( $enabled ) {

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

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

The documentation for All Products for WooCommerce Subscriptions doesn't appear to be very in-depth and so I'm unsure what, if any, functions are available to check the basket type.

Thanks

Upvotes: 1

Views: 137

Answers (1)

haidousm
haidousm

Reputation: 555

This should get the trick done. What it does is it loops over all the products in the cart, checks if they have a specific field (used by the All Products for WooCommerce Subscriptions plugin) that indicates the current product is a subscription product, and then disables the coupon field.

It disables the coupon field if any of the products are subscription products.

function hide_coupon_field( $enabled ){
    
    $cart_contents = WC()->cart->cart_contents;
    foreach ( $cart_contents as $cart_item ) {
        if ( ! empty( $cart_item[ 'wcsatt_data'][ 'active_subscription_scheme' ] ) ) {
            
            // cart contains a subscription product
            $enabled = false;
            break;
        }
    }
    
    // else keeps the field enabled
    return $enabled;
}

add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field' );

Upvotes: 1

Related Questions