phpwordpressif-statementwoocommerceproduct

Exclude multiple product IDs from WooCommerce coupons in an efficient way


Originally, I only needed to disable coupons from working on one product, so this filter worked well. However, over time, I've added to it a few times. But it looks messy!

Is there a better way to format this?

add_filter( 'woocommerce_coupon_is_valid_for_product', 'quadlayers_exclude_product_from_product_promotions', 9999, 4 );
function quadlayers_exclude_product_from_product_promotions( $valid, $product, $coupon, $values ) {
    if ( 49134 == $product->get_id() ) {
        $valid = false;
    }
    if ( 49137 == $product->get_id() ) {
        $valid = false;
    }
    if ( 29873 == $product->get_id() ) {
        $valid = false;
    }
    if ( 43181 == $product->get_id() ) {
        $valid = false;
    }
    if ( 49317 == $product->get_id() ) {
        $valid = false;
    }
    if ( 114863 == $product->get_id() ) {
        $valid = false;
    }
    if ( 117949 == $product->get_id() ) {
        $valid = false;
    }
    if ( 120076 == $product->get_id() ) {
        $valid = false;
    }
    if ( 122660 == $product->get_id() ) {
        $valid = false;
    }
    if ( 129323 == $product->get_id() ) {
        $valid = false;
    }
    return $valid;
}

Solution

  • You can set your Products IDs in an array and use PHP conditional function in_array() like:

    add_filter( 'woocommerce_coupon_is_valid_for_product', 'quadlayers_exclude_product_from_product_promotions', 9999, 4 );
    function quadlayers_exclude_product_from_product_promotions( $valid, $product, $coupon, $values ) {
        $targeted_ids = array(49134, 49137, 29873, 43181, 49317, 114863, 117949, 120076, 122660, 129323);
            
        if ( in_array($product->get_id(), $targeted_ids) ) {
            $valid = false;
        }
        return $valid;
    }
    

    It should work.