I have created a custom post type called 'events' and custom date field called 'event_date' .
I was able to create archive list for custom post type using this awesome plugin
This plugin allowed me create archives list url in this format : www.example.com/2015/11/events/
Till this point every thing worked perfectly.
But I wanted to created archives by 'event_date' unlike usual by published date, so made some changes in the above mentioned plugin and was able to create an archive list by 'event_date'.
I am unable to view posts when I click on the link : www.example.com/2016/09/events/
Now when I am writing this question the month is november so for events in november it returns correct posts.
I have used pre_get_post to get event by 'event_date' but it still returns posts by published date. Here is my code to get the posts:
function custom_events_query( $query ) {
if ( $query->is_main_query() && $query->is_archive && !is_admin()&& is_post_type_archive('events') && $query->query_vars['m']!='') {
$query->set( 'post_type', 'events' );
$query->set( 'meta_key', 'event_date' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );
$query->set( 'post_per_page', 10 );
unset($query->query_vars['year']);
unset($query->query_vars['monthnum']);
unset($query->query_vars['day']);
$meta_query = array(
array(
'key' => 'event_date',
'value' => array(date('Y-m-d',strtotime($query->query_vars['m'].'01')),date('Y-m-d',strtotime($query->query_vars['m'].'31'))) ,
'compare' => '>=',
)
);
$query->set( 'meta_query', $meta_query );
}
return $query;
}
add_filter( 'pre_get_posts', 'custom_events_query' );
Why does it still return posts by published date when I have
unset($query->query_vars['year']);
unset($query->query_vars['monthnum']);
Here is a link to the output which i get when trying to open: http://www.example.com/2016/08/events/
I have started using wordpress very recently and I am not sure about using pre_get_post correctly. It would be great if you could help me with this final step. Thanks in advance. Forgive me for trying to explain my entire journey through events, I just wanted to make sure I was doing things correctly.
pre_get_posts
function passes all of theif
conditions?var_dump( $wp_query )
in the template, it will show you the value of all query vars and the SQL query being sent to the database.