Sorting out of stock WooCommerce products in WordPressThere are many instances where online store owners wish to have out of stock products continue to be displayed so that customers can back-orders products or to show the types of products that have been sold.  One problem with doing this is the clutter of out of stock products mixed-in with the for sale products.  Thankfully, sorting out of stock WooCommerce products to the bottom of the product category isn’t difficult with a little bit of code. The code snippet below is to be pasted in your theme’s functions.php file implement the sorting out of stock WooCommerce products. Note that if you are using a child theme this code should be put in your child theme’s functions.php file and not the parents theme’s functions.php file. Any function placed in the parent theme will be over-written when the theme is updated. This is another reason why creating a child theme is so important. If you missed our WooCommerce tutorial on creating child themes please check it out.

Sorting Out of Stock WooCommerce Products code

/**
* Sorting out of stock WooCommerce products - Order product collections by stock status, in-stock products first.
*/
class iWC_Orderby_Stock_Status
{
public function __construct()
{
// Check if WooCommerce is active
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
add_filter('posts_clauses', array($this, 'order_by_stock_status'), 2000);
}
}
public function order_by_stock_status($posts_clauses)
{
global $wpdb;
// only change query on WooCommerce loops
if (is_woocommerce() && (is_shop() || is_product_category() || is_product_tag())) {
$posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) ";
$posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
$posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where'];
}
return $posts_clauses;
}
}
new iWC_Orderby_Stock_Status;
/**
* END - Order product collections by stock status, instock products first.
*/
X

2 Comments. Leave new

You must be logged in to post a comment.