I’m modifying the query for archives pages so that the posts showing up on year, month or day pages are queried by there custom field (start-date
and end-date
) and are sorted by custom star-date
field. Here’s my code:
function display_posts_on_archive_pages( $query ) {
if( $query->is_main_query() && $query->is_archive && !is_admin() ) {
$year = $query->query['year'];
$month = isset($query->query['monthnum']) ? $query->query['monthnum'] : NULL;
$day = isset($query->query['day']) ? $query->query['day'] : NULL;
if($query->is_year){
$value = array(mktime(0, 0, 0, 01, 01, $year), mktime(23, 59, 59, 12, 31, $year));
$compare = 'BETWEEN';
} else if($query->is_month){
$next_month = sprintf("%02d",$month+1);
$value = array(mktime(0, 0, 0, $month, 01, $year), mktime(0, 0, 0, $next_month, 01, $year));
$compare = 'BETWEEN';
} else if($query->is_day){
$value = mktime(0, 0, 0, $month, $day, $year);
$compare = '<=';
$compare2 = '>=';
}
$meta_query[] =
array(
'key' => 'if_events_startdate',
'value' => $value,
'compare' => $compare,
);
if($query->is_month){
$meta_query[] =
array(
'key' => 'if_events_enddate',
'value' => $value,
'compare' => $compare,
);
$meta_query['relation'] = 'OR';
}
if($query->is_day){
$meta_query[] =
array(
'key' => 'if_events_enddate',
'value' => $value,
'compare' => $compare2
);
$meta_query['relation'] = 'AND';
}
$query->set( 'year','' );
$query->set( 'monthnum', '' );
$query->set( 'day','' );
if(!$query->is_month){
$query->set( 'meta_key', 'if_events_startdate' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'ASC' );
}
$query->set( 'posts_per_page', '10' );
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', 'display_posts_on_archive_pages' );
For Year and Day pages everything is OK, but for Month pages the sorting won’t work (that’s why I’ve put the if ( ! $query->is_month ) {
in the $query->set. At the end for month pages I have the right posts but without the start-date sorting. And if I delete the if ( ! $query->is_month ) {
statement I get posts even if they are not included in the month queried (ex.: posts of September in August…)
If anyone has a clue… didn’t find my solution for the moment.
Thanks