frontendeveloper
8/1/2017 - 11:02 PM

limit posts per category/archive page

limit posts per category/archive page


// The below code will limit the number of posts shown on ALL categories. Simply copy and paste it into your themes functions.php file.
add_filter('pre_get_posts', 'limit_category_posts');
function limit_category_posts($query){
    if ($query->is_category) {
        $query->set('posts_per_page', 5);
    }
    return $query;
}


// This can also apply to archives, just change the word “category” to archive, like this:
add_filter('pre_get_posts', 'limit_archive_posts');
function limit_archive_posts($query){
    if ($query->is_archive) {
        $query->set('posts_per_page', 5);
    }
    return $query;
}


// Or if you would like to limit the number of posts within a particular category:
add_filter('pre_get_posts', 'per_category_basis');
function per_category_basis($query){
    if ($query->is_category) {
        // category named 'books' show 12 posts
        if (is_category('books'){
            $query->set('posts_per_page', 12);
        }
        // category With ID = 32 show only 5 posts
        if (is_category('32'){
            $query->set('posts_per_page', 5);
        }
    }
    return $query;
}


// This can also be achieved by placing the following code before the loop in the category/archive template file…
global $query_string;
query_posts("{$query_string}&posts_per_page=5");