📅  最后修改于: 2023-12-03 14:48:34.227000             🧑  作者: Mango
In this article, we will discuss how to move out of stock products to the bottom of the product list in a WooCommerce store powered by WordPress. We will provide a PHP solution to achieve this functionality.
To implement this solution, you should have the following:
We will utilize the pre_get_posts
action hook provided by WordPress to modify the product query. By changing the order and sorting parameters of the query, we can move the out of stock products to the bottom of the product list.
functions.php
file or create a custom plugin file./**
* Move out of stock products to the bottom of the product list.
*
* @param WP_Query $query The query object.
*/
function move_out_of_stock_to_bottom( $query ) {
// Check if we are on the main WooCommerce product query.
if ( $query->is_main_query() && $query->is_post_type_archive( 'product' ) ) {
$query->set( 'meta_key', '_stock_status' ); // Sort by stock status.
$query->set( 'orderby', 'meta_value title' ); // Sort first by stock status and then by title.
$query->set( 'order', 'ASC' ); // Sort in ascending order.
}
}
add_action( 'pre_get_posts', 'move_out_of_stock_to_bottom' );
The pre_get_posts
action hook is fired before the main query occurs. In our implementation, we check if the query is for the main WooCommerce product query and the product post type archive.
Once the condition is met, we use the set()
method of the WP_Query
object to modify the query parameters. We set the meta_key
to _stock_status
, which refers to the stock status of the product. This ensures that the products are sorted based on their stock status.
Next, we set the orderby
parameter to meta_value title
to sort first by the stock status and then by the product title. Finally, we set the order
parameter to 'ASC'
to sort the products in ascending order.
By implementing this code snippet and refreshing the product listing page, you will find that out of stock products are moved to the bottom of the list.
In this guide, we discussed how to move out of stock products to the bottom of the product list in a WooCommerce store powered by WordPress. By utilizing the pre_get_posts
action hook and modifying the query parameters, we were able to achieve this functionality in an efficient manner. Feel free to customize the code snippet as per your specific requirements.