Custom sorting for WooCommerce products order by

I had to really customize the order by of the main WP query. Finally looks like I nailed it.

function pn_woocommerce_product_query( WP_Query $wp_query ) {
if ( $wp_query>get( 'orderby' ) == 'menu_order title' ) {
$wp_query>set( 'meta_query', [
'relation' => 'AND',
'internal_stock' => [
'key' => '_manage_stock',
'compare' => 'EXIST',
],
'stock_status' => [
'key' => '_stock_status',
'compare' => 'EXIST',
],
'price' => [
'key' => '_price',
'compare' => 'EXISTS',
],
] );
$wp_query>set( 'orderby', [
'internal_stock' => 'ASC',
'stock_status' => 'ASC',
'price' => 'ASC',
] );
}
}
add_action( 'woocommerce_product_query', 'pn_woocommerce_product_query' );
function pn_posts_orderby_request( $orderby ) {
// Output based on pn_woocommerce_product_query()
if ( $orderby == 'CAST(pn_postmeta.meta_value AS CHAR) ASC, CAST(mt1.meta_value AS CHAR) ASC, CAST(mt2.meta_value AS CHAR) ASC' ) {
$orderby = "pn_postmeta.meta_value ASC, FIELD (mt1.meta_value, 'instock', '3days', 'outofstock'), mt2.meta_value ASC";
}
return $orderby;
}

view raw
order-by-field.sql
hosted with ❤ by GitHub

Author: Michal Zuber

Full stack developer, biker and rollerblader. Owner and developer at https://nevilleweb.sk/ Co-founded http://neville.sk/ Blog at https://michalzuber.wordpress.com/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s