Categories

Wednesday, November 6, 2024
#919814419350 therichposts@gmail.com
WoocommerceWoocommerce HooksWordpress

Woocommerce – Hide out-of-stock products when using ‘sorting’ in category

Woocommerce - Hide out-of-stock products when using ‘sorting’ in category

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:

  1. WooCommerce Hooks
  2. WordPress Tricks
  3. WordPress Hooks
  4. Dokan

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

  1. Condition for Sorting: This code checks if a sorting option is applied by examining the orderby URL parameter (e.g., ?orderby=price). If sorting is active, it only retrieves in-stock products.
  2. Meta Query for Stock Status: By adding a _stock_status meta query with the value 'instock', WooCommerce filters out out-of-stock items during sorting.

Steps to Use

  1. Add this code to your theme’s functions.php file.
  2. 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

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.