📌  相关文章
📜  wp wc php out of stock product to bottom - PHP(1)

📅  最后修改于: 2023-12-03 14:48:34.227000             🧑  作者: Mango

WP WooCommerce PHP: Out of Stock Product to Bottom

Introduction

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.

Requirements

To implement this solution, you should have the following:

  • WordPress installation with WooCommerce plugin activated.
  • Basic knowledge of PHP and WordPress development.
Approach

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.

Implementation
  1. Open your theme's functions.php file or create a custom plugin file.
  2. Add the following code snippet to implement the functionality:
/**
 * 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' );
  1. Save the file.
Explanation

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.

Conclusion

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.