0

Filtering my custom post type by published year. I have something like this:

Filter posts for 2015 / 2016.

The years are links which redirecting with $_GET vars like '?year=2015' and '?year=2016'

In the custom page i have this:

$year = isset($_GET['year']) ? $_GET['year'] : '';

if ($year == '2015') {
    $the_query = new WP_Query('year=2015&post_type=events');
} else {
    $the_query = new WP_Query('post_type=events');
}

But if i click the 2015 year i'm redirecting to 404 page. I tried make query like this $the_query = new WP_Query('year=2015&post_type=events'); and it works, but cannot make it work with the GET or is there a better way to do that? (sorry for my English)

Also tried this:

$year = isset($_GET['year']) ? $_GET['year'] : '';

$the_query = new WP_Query('year='. (int)$year .'&post_type=events');

And here is problem that my 2016 posts are filtering but if i pass 2015 to GET parametr im redirecting to 404 page.

  • Are you sure you have any posts in 2015? – Robbert Oct 16 '16 at 20:30
  • @Robbert Of course, i have posts in 2014, 2015, 2016. – Valijon Rahimov Oct 16 '16 at 20:40
  • Have you refreshed your permalinks already? – Robbert Oct 16 '16 at 20:42
  • @Robbert What do you mean by that? – Valijon Rahimov Oct 16 '16 at 20:42
  • In your admin dashboard under settings -> permalinks you can save your permalink structure. While doing this, your permalinks will be reflushed. Sometimes this will help with 404 pages. – Robbert Oct 16 '16 at 20:44
0

I recommend to hook into the pre_get_posts() function to change the query by adding this code to your functions.php file:

<?php
function filter_by_date( $query ) {

   if ( ! is_admin() && $query->is_main_query() ) {

      if ( isset( $_GET['year'] ) ) {
         $query->set( 'year', $_GET['year'] );
         $query->set( 'post_type', 'events' );
      }
   }

   return $query;

}
add_action( 'pre_get_posts', 'filter_by_date' );
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.