I use the built in WooCommerce filter by attribute widget which works for what I need, but my issue is, that if I filter on a size, I get all products with that size as an attribute, also when they are out of stock…
My products are created as a variable product with variations on size and color
What I want, is to filter a size and only display products in that size that is in stock.
4
Answers
You can hide out of stock products by checking the option of "Out of stock visibility" on the Settings page:
Woocommerce > Settings > Product > Inventory
It may not be possible for variable products and their variations (but only for other product types).
It can only works for variable products when stock management is handled by the product variation itself (but not by the variations).
Note that WooCommerce product query doesn’t handle post type ‘product_variation’, but only post type ‘product’.
To exclude out of stock products using widget filters (except for variable products) you can use:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
I’ve used this code for my stores to hide product sizes that are not in stock whilst filtering.
filter_size will be converted in array if many filter being selected.
As for product variations, best if its stored in an array as well and use array_intersect to search if one of the selected item available in stock.
This code works for me