Repository › Forums › Support › WooCommerce Extended Coupon Features PRO › Add 2 different products and get 5% discount on specific product › Reply To: Add 2 different products and get 5% discount on specific product

#17715
Soft79
Keymaster

This snippet should work.

Create a 5% discount coupon that only applies to product A.

Paste the snippet in your child theme’s functions.php and replace the value after $required_cat with category B’s id and replace the value after $coupon_code with the coupon code. The snippet will invalidate the coupon if there’s no item from category B in the cart.


add_filter( 'woocommerce_coupon_is_valid', function( $valid, $coupon, $wc_discounts ) {
    $required_cat = 6666;
    $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 );
    }
    //Get array of all cart product and variation ids
    $product_cats = array();
    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();
        }
        $product_cats = array_merge( $product_cats, wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) ) );
    }
    if ( ! in_array( $required_cat, $product_cats ) ) {
        $valid = false;
    }
    return $valid;
}, 10, 3 );

Note: untested.