Modify WooCommerce Ajax Variation Threshold

If you're using WooCommerce and using variations, you might find that there are times when it seems customers might be able to make selections which are not actually available. One of the big reasons was an adjustment within the WooCommerce core to lower the number of variations to trigger ajax to 30. While this will work for products with a low number of variations, some with a larger amount might not work as expected. To adjust this, we can add a filter to the woocommerce_ajax_variation_threshold hook like this:

# Adjust the number variations to trigger the use of Ajax
function idww_wc_ajax_variation_threshold( $qty, $product ) {
  return 100;
add_filter( 'woocommerce_ajax_variation_threshold', 'idww_wc_ajax_variation_threshold', 10, 2);

This will set the threshold to 100 across the store. Depending on the number of products and the amount of variations, this could be fine for your store, but you might wish for some more granular control.

To create a way to override this setting at the product level, you could add a metabox with an option to override and a input for the number to override with. This would allow you to override only those products with more than 30 variations. Then use the add_filter setup above to check if that option is set and return the number for that product if not the default of 30, otherwise use the default.

Another option could be to calculate the number of variations programmatically with some code and if more than 30, trigger a call to this function to return that amount.