Custom WP query ORDER BY with FIELD()
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment