To move WooCommerce products where all variations are out of stock to the end of the shop page and homepage, we need to connect to the default WordPress and WooCommerce hooks and adjust the product sorting priority based on their inventory status. Stay with Radib until the end of this tutorial.
Step-by-step explanation:
- Identify products where all variations are out of stock.
- Modify the hook related to the display order of products in WooCommerce.
- Move out-of-stock products to the end of the list.
Complete code to add to the functions.php
file:
To address the issues you mentioned, we need to implement a more efficient and optimized solution for managing product displays in WooCommerce. The main goal is to move products that are out of stock or have all variations out of stock to the end of the list without affecting the store's performance.
Purchase high-speed cPanel and DirectAdmin WordPress hosting at the best price from Radib, click here.
Optimization:
- Using direct database queries: Instead of using complex meta queries.
- Smart filtering in
posts_clauses
: The most optimal way to apply changes to query order without slowing down the store.
Proposed Code:
// Move out-of-stock products to the end of the shop list
add_filter('posts_clauses', 'move_out_of_stock_products_to_end', 10, 2);
function move_out_of_stock_products_to_end($clauses, $query) {
if (!is_admin() && is_woocommerce() && $query->is_main_query()) {
global $wpdb;
// Condition to check out-of-stock products
$stock_status_table = "{$wpdb->prefix}postmeta";
$clauses['join'] .= " LEFT JOIN $stock_status_table AS stock_status_meta ON ({$wpdb->posts}.ID = stock_status_meta.post_id AND stock_status_meta.meta_key = '_stock_status')";
// Move in-stock products to the beginning of the list
$clauses['orderby'] = "CASE WHEN stock_status_meta.meta_value = 'outofstock' THEN 1 ELSE 0 END ASC, " . $clauses['orderby'];
}
return $clauses;
}
Explanation:
- This code uses the
posts_clauses
hook, which directly modifies the main WooCommerce SQL query. - Out-of-stock products are moved to the end of the list using the
_stock_status
metadata. - The SQL
CASE WHEN
condition ensures that out-of-stock products are placed at the end.
Purchase an affordable VPS from Radib, click here.
Advantages:
- Optimized and fast: Due to the direct modification of the SQL query.
- No use of complex meta queries: Improved performance for large stores.
a. Do you need to move products based on additional priorities such as date or category?
b. Would you like further explanation on how to optimize this code?
Stay in touch with Radib's experts and developers via support ticket.