Skip to content

Instantly share code, notes, and snippets.

@mikaelz
Created July 20, 2019 04:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaelz/aa0611a4e1eb3fa59b417322dec2baef to your computer and use it in GitHub Desktop.
Save mikaelz/aa0611a4e1eb3fa59b417322dec2baef to your computer and use it in GitHub Desktop.
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