I have been able to show out of stocks products at the end with the default sorting using this snippet:
/**
* @snippet Order out of stock products at the end - WooCommerce
* @author Sebastian Velandia
* @compatible WooCommerce 3.8.0
*/
add_filter('posts_clauses', 'order_by_stock_status');
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() || is_product_taxonomy())) {
$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;
}
This works okey with the default sorting, but when you apply other sorting criteria like for example, by price, then it stops working and out of stock products become visible again from the beginning of the catalog.
How to fix this snippet to always display the out of stock products at the end despite the sorting applied in woocommerce catalog?
2
Answers
So this seems to work in testing. The orderby clause when you change the WooCommerce sort order on the shop page is superseded by the ordering. So this uses the filter
woocommerce_get_catalog_ordering_args
to append to all sorting queries your orderby function before the choice from the dropdown.this code worked for me (put in functions.php of your theme)