Overriding WooCommerce AJAX Variations Limit
Recently while working on a customer’s e-commerce site, we noticed a problem where all variations were not showing on some of the product pages. Some products were showing variations that did not exist, while some where working as expected. In this post I’ll share the solution I found for overriding WooCommerce AJAX variations limit.
As background, this particular store has three product attributes:
For some of the designs, her variations could very easily grow to several dozen:
- 3 Colors (Gray, Black, White)
- 4 Styles (Shirt, Onesie, Tank, Thermal)
- 8 Sizes (3M, 6M, 9M, 12M, 2T, 4T, 6, 8)
However, everything is made by hand and and not all designs and colors are available on all styles. For example, the store owner creates infant onesies, but only in white. She also offers toddler thermal shirts, but only in gray. So it’s very important that customers be limited to the proper variations on her product pages to prevent them from ordering invalid products.
The problem we were seeing is that the front end product pages were not always enforcing this. In some cases, a customer could order a gray onesie even though that’s never available. After some research I found the problem was related to a little known filter related to WooCommerce AJAX variations limit.
After a fair amount of searching, I stumbled on this variations limit. Turns out, the fine folks at WooCommerce expected this limit might be a problem and provided a hook to override the behavior. Adding the following snippet of PHP code to the functions.php file in the child theme solved the problem:
* Fix for issue where too many variations causes the front end to not pre-load
* all variations and rely on AJAX.
function custom_wc_ajax_variation_threshold( $qty, $product )
add_filter( 'woocommerce_ajax_variation_threshold', 'custom_wc_ajax_variation_threshold', 10, 2 );
Note that the filter also passes you the product reference. The shop I worked on can get by with a static number, but you could potentially return a dynamic threshold based on product category, name, tag, or other data. You can read more about the filter here.