1

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.

  • Go and check out this answer and this anwer. This will definitly shed some light on your question – Pieter Goosen Apr 8 '14 at 4:18
  • This answer is your answer, maybe you use the search before you ask. – bueltge Apr 8 '14 at 7:43
0

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.