Show Different Number Of Posts 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 “song”, just open the functions.php file in your theme folder and insert these line into it:

1.  add_action('pre_get_posts', 'diff_post_count_per_cat');
2.   
3.  function diff_post_count_per_cat() {
4.      if (is_admin()) return;
5.   
6.      $cat = get_query_var('category_name');
7.      switch ($cat) {
8.          case 'wordpress':
9.              set_query_var('posts_per_page', 5);
10.            break;
11.        case 'wordpress/song':
12.            set_query_var('posts_per_page', 2);
13.            break;   
14.    }
15.}

Change “wordpress” and “song” 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/song” in the example below).


No comments:

Post a Comment