move-out-of-stock.php
· 1.2 KiB · PHP
Sin formato
// move out of stock products to end of loop in WooCommerce Archives
add_action( 'woocommerce_product_query', 'custom_woocommerce_product_query' );
function custom_woocommerce_product_query( $q ) {
// Get any existing meta query from the query
$meta_query = $q->get('meta_query');
// Add our condition
$stock_status_meta_query = array(
'relation' => 'OR',
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
),
array(
'key' => '_stock_status',
'compare' => 'NOT EXISTS', // This ensures compatibility with variations
),
);
// If there's already a meta_query, we add ours to it. If not, we create a new one.
if (!empty($meta_query)) {
$meta_query[] = $stock_status_meta_query;
} else {
$meta_query = array($stock_status_meta_query);
}
// Set the modified meta query back
$q->set('meta_query', $meta_query);
// Order by stock status first
$q->set('orderby', array('meta_value' => 'ASC', 'date' => 'DESC'));
// This ensures out-of-stock products are listed last
$q->set('meta_key', '_stock_status');
$q->set('order', 'ASC');
}
| 1 | // move out of stock products to end of loop in WooCommerce Archives |
| 2 | |
| 3 | add_action( 'woocommerce_product_query', 'custom_woocommerce_product_query' ); |
| 4 | function 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 |