Show a different number of posts per page depending on context (e.g., homepage, search, archive)

I believe the best way to do this in a plugin is to run the following sample function when the pre_get_posts action hook is encountered. The $wp_query object is available, meaning your conditional tags are available, but before WordPress gets the posts, which means you are changing query vars prior to the first query being run, rather than adding a second query like when query_posts() is used in a theme file.

function custom_posts_per_page($query) {
    if (is_home()) {
        $query->set('posts_per_page', 8);
    }
    if (is_search()) {
        $query->set('posts_per_page', -1);
    }
    if (is_archive()) {
        $query->set('posts_per_page', 25);
    } //endif
} //function

//this adds the function above to the 'pre_get_posts' action     
add_action('pre_get_posts', 'custom_posts_per_page');

Leave a Comment