最后活跃于 1713289486

move-out-of-stock.php 原始文件
1// move out of stock products to end of loop in WooCommerce Archives
2
3add_action( 'woocommerce_product_query', 'custom_woocommerce_product_query' );
4function custom_woocommerce_product_query( $q ) {
5 // Get any existing meta query from the query
6 $meta_query = $q->get('meta_query');
7
8 // Add our condition
9 $stock_status_meta_query = array(
10 'relation' => 'OR',
11 array(
12 'key' => '_stock_status',
13 'value' => 'instock',
14 'compare' => '=',
15 ),
16 array(
17 'key' => '_stock_status',
18 'compare' => 'NOT EXISTS', // This ensures compatibility with variations
19 ),
20 );
21
22 // If there's already a meta_query, we add ours to it. If not, we create a new one.
23 if (!empty($meta_query)) {
24 $meta_query[] = $stock_status_meta_query;
25 } else {
26 $meta_query = array($stock_status_meta_query);
27 }
28
29 // Set the modified meta query back
30 $q->set('meta_query', $meta_query);
31
32 // Order by stock status first
33 $q->set('orderby', array('meta_value' => 'ASC', 'date' => 'DESC'));
34
35 // This ensures out-of-stock products are listed last
36 $q->set('meta_key', '_stock_status');
37 $q->set('order', 'ASC');
38}
39