Created
July 20, 2019 04:39
-
-
Save mikaelz/aa0611a4e1eb3fa59b417322dec2baef to your computer and use it in GitHub Desktop.
Custom WP query ORDER BY with FIELD()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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