How to include wordpress pages in archives

WordPress archives are very useful in providing users and search engine bots like Googlebot a great way to browse all content on a wordpress site. By default wordpress only included wordpress post_type=post on monthly archive pages (e.g. /2015/08 ). Here are the steps to include post_type=page also on wordpress archive pages.

Add the following code to your plugin (you can create a site plugin for your blog):

function pre_get_posts_date_archive($query ) {
  // For archives, year and monthnum should be present in query object
  if ($query->get('year') && $query->get('monthnum')) {
    $query->set('post_type', array('post', 'page'));
  }
}

Noe that we set post_type to include both post and page here.

Now add the action pre_get_posts_date_archive to the wordpress hook pre_get_posts. This is how overall code should look like:

function pre_get_posts_date_archive($query ) {
  // For archives, year and monthnum should be present in query object
  if ($query->get('year') && $query->get('monthnum')) {
    $query->set('post_type', array('post', 'page'));
  }
}
add_action('pre_get_posts', 'pre_get_posts_date_archive');

Now you can visit any of you archive page (e.g. /2015/09/) and you should be able to see wordpress posts and pages both on archive pages.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments