WooCommerce: Add a Filter Option in the Default Sorting

In a WooCommerce online store, providing customers with efficient ways to find products that are currently in stock can greatly enhance their shopping experience. By sorting products based on stock status, you can help users quickly identify available items and streamline their purchasing process. In this guide, we’ll demonstrate how to implement a sorting option for “in-stock” products in your WooCommerce shop.

* Snippet Name: Adding Order by stock option in default sorting dropdown
* Snippet Author: wpsnippets.dev*/

//Add "Sort by stock status: in stock" option to the default sorting dropdown
function wps_adding_stock_option($options) {
	$options['in-stock'] = 'Sort by stock status : in stock';
	return $options;

add_filter('woocommerce_catalog_orderby', 'wps_adding_stock_option');

//Modify sorting query to prioritize "in stock" products
function wps_sorting_product_by_status($args) {
	if( isset( $_GET['orderby'] ) && 'in-stock' === $_GET['orderby'] ) { // Check if the sorting option selected is 'in-stock'
		$args['meta_key'] = '_stock_status';
		$args['orderby'] = array( 'meta_value' => 'ASC' ); // Show products in stock first. Change 'ASC' to 'DESC' to show out of stock products first.
	return $args;
add_filter('woocommerce_get_catalog_ordering_args', 'wps_sorting_product_by_status');

Code Explanation

  • This code adds a sorting option for “in stock” products to the default sorting dropdown in WooCommerce and modifies the sorting query to prioritize products with the “in stock” status.
  • The first function wps_adding_stock_option adds a new sorting option to the default sorting dropdown in WooCommerce. It modifies the array of sorting options by adding a new option with the key ‘in-stock‘ and the label ‘Sort by stock status: in stock.’
  • The second function wps_sorting_product_by_status modifies the product sorting query based on the selected sorting option. It checks if the selected sorting option is ‘in-stock.’ If it is, it modifies the query arguments to sort products by their stock status. It sets the meta key to ‘_stock_status‘ (which indicates the stock status of the product) and orders the products by their stock status in ascending order. You can change ‘ASC’ to ‘DESC’ if you want Out of Stock products to appear first.
  • These functions are then hooked to WooCommerce filters woocommerce_catalog_orderby and woocommerce_get_catalog_ordering_args respectively, to apply the custom sorting functionality.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top