Using is_main_query to select custom post type on certain page

The is_home() conditional returns true when the currently displayed page is the blog posts index. If you want to target the site front page specifically instead, you need to use is_front_page():

function wpse83754_filter_pre_get_posts( $query ) {
    if ( $query->is_main_query() && is_front_page() ) {
        $query->set( 'post_type', array( 'home_portfolio' ) );
    }
}
add_action( 'pre_get_posts', 'wpse83754_filter_pre_get_posts' );

Also, you don’t have to append $query-> to calls to is_home(), is_front_page(), etc. You do need to do so for is_main_query(), since you want to ensure that the query being filtered is specifically the main query, since any given page will have multiple queries.

So, if you want to target a specific page, just call is_page( $id ):

function wpse83754_filter_pre_get_posts( $query ) {
    if ( $query->is_main_query() && is_page( $id ) ) {
        $query->set( 'post_type', array( 'home_portfolio' ) );
    }
}
add_action( 'pre_get_posts', 'wpse83754_filter_pre_get_posts' );

Leave a Comment