Different Ways to Query Custom Post Types?

I’m using this code to use custom post types like regular post:

add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

function add_my_post_types_to_query( $query ) {
if ( is_home() && $query->is_main_query() )
    $query->set( 'post_type', array( 'post', 'miss_behave', 'emily_davies','gemma_patel','poppy_smythe' ) );
return $query;
}

But I also saw this code to display custom post types:

Read More
$query = new WP_Query( array(
'post_type' => array( 'post', 'page', 'movie', 'book' )
) );

I’m wondering what the differences are between the two methods.

Thanks.

Related posts

Leave a Reply

2 comments

  1. The first way, using the pre_get_posts action will modify the main query before the page loads. The second way will create a new query. It is much better to alter the main query than to create a new query.

  2. pre_get_posts

    pre_get_posts is used to alter the main query for posts so the is_home() conditional tag will work.

    You can also use the is_post_type_archive() conditional tag to alter the query on CPT archives like so.

    add_action( 'pre_get_posts', 'limit_cpt_items' );
    function limit_cpt_items( $query ) {
    
    if( $query->is_main_query() && !is_admin() && is_post_type_archive( 'your-cpt' ) ) {
        $query->set( 'posts_per_page', '24' );
        }
    
    }
    

    WP_Query

    You would use a new WP_Query for page requests including conditional tags for pages like is_page(), is_page_template() and is_front_page() which will NOT work with pre_get_posts which is runs before WP_Query.