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:
$query = new WP_Query( array(
'post_type' => array( 'post', 'page', 'movie', 'book' )
) );
I’m wondering what the differences are between the two methods.
Thanks.
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.
pre_get_posts
pre_get_posts
is used to alter the main query for posts so theis_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.
WP_Query
You would use a new WP_Query for page requests including conditional tags for pages like
is_page()
,is_page_template()
andis_front_page()
which will NOT work with pre_get_posts which is runs before WP_Query.