Modifying the main WordPress query the right way

Introducing pre_get_posts

With pre_get_posts you can modify the main query anywhere on your site without ever touching a single file within your theme and pagination will continue to work as expected. pre_get_posts is an action hook that is called after the query variable object is created, but before the actual query is run. This means your changes are directly to the object itself and not during run time which offers a lot more control and flexibility.


// My function to modify the main query object
function my_modify_main_query( $query ) 
{
    if ( $query->is_home() && $query->is_main_query() )  
    { 
        // Run only on the homepage
        $query->query_vars[‘cat’] = -2; // Exclude my featured category because I display that elsewhere
        $query->query_vars[‘posts_per_page’] = 5; // Show only 5 posts on the homepage only
    }
}

// Hook my above function to the pre_get_posts action
add_action( ‘pre_get_posts’, ‘my_modify_main_query’ );

Just place your own version of this code in a site functionality plugin or your child themes functions.php file and you’re done.
Get more info and useful samples about ‘pre_get_posts’ at pre_get_posts action hook at WordPress codex.

Share            
X
                                                                                                        

Leave a Reply

Your email address will not be published. Required fields are marked *