Sort out of stock products at the end in search results page
-
Hi,
I am trying to sort out of stock products at the end of product list in search results page, but I can’t. I have add this code:
function _nok_order_by_stock_status($posts_clauses, $query) {
// Check if 'orderby' exists in the posts_clauses and if 'order' request parameter is set to 'desc' if (isset($posts_clauses['orderby']) && isset($_REQUEST['order']) && strtolower($_REQUEST['order']) == "desc") { $posts_clauses['orderby'] = str_replace("ASC", "DESC", $posts_clauses['orderby']); } // Check if the query is the main query and if it's a product category, tag, taxonomy or shop page if ($query->is_main_query() && ( (function_exists('is_product_category') && is_product_category()) || (function_exists('is_product_tag') && is_product_tag()) || (function_exists('is_product_taxonomy') && is_product_taxonomy()) || (function_exists('is_shop') && is_shop()) || is_search() )) { global $wpdb; // Join the postmeta table for stock status and price $posts_clauses['join'] .= " LEFT JOIN ( SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_stock_status' ) istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) LEFT JOIN ( SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_price' ) prezzo ON ($wpdb->posts.ID = prezzo.post_id)"; // Modify the orderby clause to prioritize out of stock products with a non-zero price $posts_clauses['orderby'] = " CASE WHEN istockstatus.meta_value = 'outofstock' AND prezzo.meta_value != 0 THEN 1 END ASC, " . $posts_clauses['orderby']; } return $posts_clauses; } // Add the function to the 'posts_clauses' filter with a priority of 2000 add_filter('posts_clauses', '_nok_order_by_stock_status', 2000, 2);
It works perfectly on product categories, but in search results nothing goes right.
What can I do?
Please help,
thanks in advance.
Viewing 5 replies - 1 through 5 (of 5 total)
Viewing 5 replies - 1 through 5 (of 5 total)
- The topic ‘Sort out of stock products at the end in search results page’ is closed to new replies.