Each of the wordpress post has one custom field as match_time. The value of match_time can be finished/live/not_started. I want to show posts which has match_time "live" on top, and then posts of match_time "not_started" and then "finished" posts. How to do it?
1 Answer
This worked for me as long as it's run only on the appropriate query. The key is MySQL's FIELD()
function, which lets you specify an arbitrary ordering.
add_action( 'pre_get_posts', 'add_match_times_to_query' );
function add_match_times_to_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'meta_query', array(
'match_time' => array(
'key' => 'match_time',
'compare' => 'EXISTS',
),
) );
add_filter( 'posts_orderby', 'edit_posts_orderby_match_times' );
}
}
function edit_posts_orderby_match_times( $orderby ) {
return 'FIELD(meta_value, "live", "not_started", "finished") ASC';
}