Hello guys how are you? Welcome back on my blog therichpost.com. Guys today in this blog post I am going to tell you, Woocommerce – Hide out-of-stock products when using ‘sorting’ in category.
Guys if you are new in WordPress or in WooCommerce then please check the below links for some good tutorials:
Guys To hide out-of-stock products specifically when using sorting options in a WooCommerce category, we can apply a conditional filter based on whether a sort option is selected.
This can be done by targeting the WooCommerce sorting query and adding a filter that removes out-of-stock items. Here’s how you can achieve it:
add_action('woocommerce_product_query', 'hide_out_of_stock_when_sorting');
function hide_out_of_stock_when_sorting($q) {
if (is_product_category()) {
// Check if sorting is applied
if (isset($_GET['orderby']) && !empty($_GET['orderby'])) {
$meta_query = $q->get('meta_query');
// Add a condition to hide out-of-stock products
$meta_query[] = array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '='
);
$q->set('meta_query', $meta_query);
}
}
}
Explanation
- Condition for Sorting: This code checks if a sorting option is applied by examining the
orderbyURL parameter (e.g.,?orderby=price). If sorting is active, it only retrieves in-stock products. - Meta Query for Stock Status: By adding a
_stock_statusmeta query with the value'instock', WooCommerce filters out out-of-stock items during sorting.
Steps to Use
- Add this code to your theme’s
functions.phpfile. - Clear any site cache or WooCommerce transients to see the changes.
This code should keep out-of-stock products hidden whenever a sorting option is selected in a category page. Let me know if this approach meets your needs or if there’s anything else you’d like to adjust!
Jassa
Thanks
