Add Custom Post Type to the main query

If you want to display custom post type posts along with “default” posts in latest posts page, category page, archive page or tag page, you could you this function. Basically it will add custom post types to the main query before looping:

add_action( 'pre_get_posts', 'add_cpt_to_query' );
function add_cpt_to_query( $query ) {
        // Return if in admin area
        if( is_admin() ) {
            return $query;
        // add 'cpt' to main_query  
      if ( is_tag() && $query->is_main_query() || is_archive() && $query->is_main_query() )
        $query->set( 'post_type', array( 'post', 'page', 'custom_post_type' ) );
      return $query;

Where Do I Put This Code?

This code should be placed in the functions.php file of your active theme or a custom functions plugin.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>