I want to order products on archive pages by stock status (outofstock at the end of list) and price (lowest first). For now menu order set to default and this code is used:
add_action( 'woocommerce_product_query', 'sort_by_stock_status', 999 );
function sort_by_stock_status( $query ) {
if ( is_admin() ) return;
$query->set( 'meta_key', '_stock_status' );
$query->set( 'orderby', array( 'meta_value' => 'ASC' ) );
}
And this gives me ability to show products ordered by stock status.
I was trying to edit code so it will order by stock AND price...no luck Here is what i have tried:
add_action( 'woocommerce_product_query', 'sort_by_stock_status_and_menu_order', 999 );
function sort_by_stock_status_and_menu_order( $query ) {
if ( is_admin() ) return;
$query->set( 'meta_key', '_stock_status' );
$query->set( 'orderby', array( 'meta_value' => 'ASC', 'menu_order' => 'ASC' ) );
}
If i set menu to "order by price" i see products order only by price instock and outofstock together... Could someone please help me with this? Maybe it`s already achieved in some of your websites...))
YOU were very near… You need to make some changes in your code get multiple "orderby" arguments using one string only instead of an array (each argument is separated by a space in this unique string):
add_action( 'woocommerce_product_query', 'sort_by_stock_status_and_menu_order', 999 );
function sort_by_stock_status_and_menu_order( $query ) {
if ( is_admin() ) return;
$query->set( 'meta_key', '_stock_status' );
$query->set( 'orderby', 'meta_value menu_order' );
// $query->set( 'order', 'ASC' ); // <== 'order' argument is already "ASC" by default
}
The "order" query argument is already ASC by default, so there is no need to change it.
Code goes in functions.php file of your active child theme (or active theme). Tested and works.