add_action( 'woocommerce_product_query', 'move_out_of_stock_products_to_end' ); function move_out_of_stock_products_to_end( $query ) { if ( ! is_admin() && $query->is_main_query() && ( is_shop() || is_product_category() || is_product_tag() ) ) { // Get existing meta query $meta_query = (array) $query->get('meta_query'); // Append new meta query to include in-stock and out-of-stock products $meta_query[] = array( 'relation' => 'OR', array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ), array( 'key' => '_stock_status', 'value' => 'outofstock', 'compare' => '=' ), ); // Apply the new meta query $query->set('meta_query', $meta_query); // Order by stock status first, then by date $query->set('orderby', array( 'meta_value' => 'ASC', 'date' => 'DESC' )); $query->set('meta_key', '_stock_status'); } }