Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

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

2 Answers 2

up vote 0 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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