1

I am looking for a way to not have to manually exclude products from coupons based upon the product ID that the coupon should apply to. Thus, build an array of all product IDs in the shop that will then populate the excluded products field minus the product ID (or IDs) that the coupon does apply to.

I was thinking to use "Disable coupons & discounts from applying to defined Woocommerce products in cart" answer making some changes to it, but as I am new to WP/WC queries and functions, I didn't get something functional yet.

LoicTheAztec
  • 184,753
  • 20
  • 224
  • 275
per4manz
  • 11
  • 1

1 Answers1

1

Try the following, where:

  • you will define in the first function the array of product ids to be excluded from coupons.
  • the 2nd function will remove included products ids from the array of excluded product ids and will set that in the coupon when saved.

The code:

function my_coupons_excl_product_ids() {
    // HERE set in the array your product IDs to be excluded
    return array(17, 37, 52, 123, 124, 152, 154);
}

// On coupon save
add_action('woocommerce_coupon_options_save', 'action_coupon_options_save_callback', 10, 2);
function action_coupon_options_save_callback( $post_id, $coupon ) {
    $included_ids = (array) $coupon->get_product_ids();

    if( size_of($included_ids) > 0 ) {
        $excl_product_ids = array_diff( my_coupons_excl_product_ids(), $included_ids ); // Get the difference
        $coupon->set_excluded_product_ids( array_filter( array_map( 'intval', (array) $excl_product_ids ) ) );
        $coupon->save();
    }
}

Code goes in function.php file of your active child theme (or active theme). It should works.

LoicTheAztec
  • 184,753
  • 20
  • 224
  • 275
  • I appreciate the answer. However, I was looking for something more automated. The issue is that the excluded products can vary from coupon to coupon. Therefore, I was hoping there was a dynamic way to return all product IDs to an array, then determine which products shouldn't be excluded and then fill in the excluded products field on the coupon with the remaining product IDs. Obviously this would mean having to do a for each loop or something to compare the product ID or IDs that the coupon applies to versus the entire product list. – per4manz Apr 15 '19 at 23:00