Repository Forums Support WooCommerce Extended Coupon Features PRO Auto Coupon when a certain item is in the cart

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #19729
    andy3
    Participant

    Hello – I’m looking to see if a coupon can be auto-applied if a certain item is added to the cart. So if this item is added, then the other item in the cart of a certain brand would receive 10% off, but not the trigger item.

    Is this possible?

    Thanks,

    Andy

    #19734
    Soft79
    Keymaster

    Hi,

    You need a custom PHP snippet for that. The following snippet will only make the coupon valid if product with id 1234 is in the cart. Replace 1234 with the product id of the item that must be in the cart and replace THE_COUPON_CODE with the actual coupon code. Note: snippet has not been tested.

    
    add_filter( 'woocommerce_coupon_is_valid', function( $valid, $coupon, $wc_discounts ) {
        $required_product_id = 1234;
        $coupon_code = 'THE_COUPON_CODE';
    
        if ( strcasecmp( $coupon->get_code(), $coupon_code ) !== 0 ) {
            return $valid;
        }
    
        if ( ! class_exists( 'WJECF_WC_Discounts' ) ) {
            return $valid;
        }
    
        if ( ! $valid ) {
            return $valid;
        }
    
        if ( is_null( $wc_discounts ) ) {
            $wc_discounts = new WJECF_WC_Discounts( WC()->cart );
        }
    
        foreach ( $wc_discounts->get_items() as $item_key => $item ) {
            if ( ! $item->product ) {
                continue;
            }
    
            $product_id = $item->product->get_id();
            if ( 'product_variation' == get_post_type( $product_id ) ) {
                $product_id = $item->product->get_parent_id();
            }
    
            if ( $product_id == $required_product_id ) {
                return true;
            }
        }
    
        return false;
    }, 10, 3 );
    
Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.