Show Different Number Of Posts Per Category In WordPress

Show Different Number Of Posts Per Category In WordPress

Show Different Post Count Per Category In WordPress

WPRecipes has posted a way to set different number of posts for a WordPress category. It works nicely, but only for one category. And it uses custom query, which is not very familiar to newbies. In this post, we’ll do the same thing more simpler.

Assume that we want to show 5 posts per page for category “WordPress” and 10 posts per page for category “News”, just open the functions.php file in your theme folder and insert these line into it:

add_action('pre_get_posts', 'diff_post_count_per_cat');

function diff_post_count_per_cat() {
    if (is_admin()) return;

    $cat = get_query_var('category_name');
    switch ($cat) {
        case 'wordpress':
            set_query_var('posts_per_page', 5);
            break;
        case 'wordpress/news':
            set_query_var('posts_per_page', 2);
            break;   
    }
}

Change “wordpress” and “news” into real category names of your blog. Note that in the code above, we use category slug, not original name. If the category is a child category, don’t forget to insert full path (i.e. “wordpress/news” in the example below).

2 comments

Comments are closed.