The code I have is in my functions.php file and is displaying the custom post type 'events' posts as needed, but not sorting by the meta value 'upcoming_date'. It is not sorting in ascending order either. Moreover, is it possible to sort by 2 metavalues? Please help.
add_action("pre_get_posts", "cpt_front_page");
function cpt_front_page( $wp_query ){
//Ensure this filter isn't applied to the admin area
if(is_admin()) {
return;
}
if($wp_query->get('page_id') == get_option('page_on_front')):
$wp_query->set( 'post_type', 'events' );
$wp_query->set( 'page_id', '' ); //Empty
//Set properties that describe the page to reflect that
//we aren't really displaying a static page
$wp_query->is_page = 0;
$wp_query->is_singular = 0;
$wp_query->is_post_type_archive = 1;
$wp_query->is_archive = 1;
//sort the posts by meta value in ascending order
$wp_query->meta_key = 'upcoming_date'; // <= IS THIS RIGHT?
$wp_query->orderby = 'meta_value'; // <= IS THIS RIGHT?
$wp_query->order = 'ASC'; // <= IS THIS RIGHT?
endif;
}
This is most likely an issue with how you're storing your upcoming date and attempting to sort with it. You'll probably get the best chance of success by storing your dates in yymmdd
format, and setting orderby
to 'meta_value_num'
, so that it sorts in a numerical order rather than a textual order.
$wp_query->meta_key = 'upcoming_date';
$wp_query->orderby = 'meta_value_num';
$wp_query->order = 'ASC';
The documentation on orderby is a good reference.