By default, WordPress does not include Custom Post Types when displaying archive views of your posts. For example, if you are using a Custom Post Type for submitted posts, by default WordPress will not include the posts in category archives, tag archives, or any other type of archive. So to help, this quick tutorial provides a function that will make sure all Custom Post Types are included in all archive page views.
Step 1
Add the following function to your theme’s functions.php
file:
// USP Pro - Include CPTs in archive views
function usp_pro_include_custom_post_type_archives($query) {
if ((is_category() || is_tag()) && $query->is_archive() && empty($query->query_vars['suppress_filters'])) {
$query->set('post_type', array('post', 'usp_post')); // <-- add your CPT if needed
}
return $query;
}
add_filter('pre_get_posts', 'usp_pro_include_custom_post_type_archives');
Done!
This code is adding the “USP Post” type (e.g., usp_post
) to the results returned for archive pages. It also should include the CPT on the home page (where applicable), along with other/regular posts. To include other post types in archive views, add the name of your CPT to the array (where it says, “add your CPT”). No other modifications are required, but the sky is the limit when working with $query->set()
and pre_get_posts
— anything is possible! :)
Important! For your CPT posts to be displayed, they must be published (i.e., Post Status = “Publish”).