Allow your customers to Sort products by stock in WooCommerce

In WooCommerce you can have complete management of stock, inventory or stock of your products. You just have to activate the inventory management in the WooCommerce settings and then, for each product, indicate the amount of stock available, really simple.

Then, in your store administration, in the products screen, you can filter your products by their stock level or inventory, and so far so good.

But it turns out that in the store your customers can’t sort your products by their stock, which is sometimes important in very different types of stores.

For example, in online stores of building materials, or professional supplies, the customer will want to know if there is enough stock, if he will be able to order the quantity he needs of a particular product (screws, tiles, boards, etc.).

But we are here to provide solutions, not to tell you about problems or shortages, you already know that, don’t you?

So, here you have that wonderful code you were waiting for so that your customers can also order your products by inventory, by stock quantity.

Take note:

/* Sort by stock */ function filter_woocommerce_get_catalog_ordering_args( $args, $orderby, $order ) { switch( $orderby ) { case 'availability': $args['orderby'] = 'meta_value_num'; $args['order'] = 'DESC'; $args['meta_key'] = '_stock'; break; } return $args; } add_filter( 'woocommerce_get_catalog_ordering_args', 'filter_woocommerce_get_catalog_ordering_args', 10, 3 ); function filter_orderby( $orderby ) { $orderby['availability'] = __( 'Stock', 'woocommerce' ); return $orderby; } add_filter( 'woocommerce_default_catalog_orderby_options', 'filter_orderby', 10, 1 ); add_filter( 'woocommerce_catalog_orderby', 'filter_orderby', 10, 1 ); // Optional: Show stock function action_woocommerce_after_shop_loop_item() { global $product; echo '<div style="color: red !important; font-size: 20px !important;">' . wc_get_stock_html( $product ) . '</div>'; } add_action( 'woocommerce_after_shop_loop_item', 'action_woocommerce_after_shop_loop_item', 9, 0 );
Code language: PHP (php)

The best thing about this code is not that it works, which it does, but that it also orders the products from most to least stock, and if you want (look at the last lines) it can even show the amount of stock.

Where do I add the code? In this quick guide, I explain how you can do it, depending on your level of knowledge or “desire” …

How and where to paste PHP, JS, CSS codes and functions you find around in WordPress

How useful was this post?

Click on a smiley to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

Leave a Comment

Your email address will not be published.

Scroll to Top
Skip to content