WordPress.org

Ideas

Retrieve X number of posts per category via WP_Query

  1. Jam Viet
    Member

    Use this plugin http://wordpress.org/extend/plugins/recent-posts-from-each-category/ of course slove this problem but do you think it increase time loading blog ?

    Posted: 1 year ago #
  2. jonasscout
    Member

    I'm concerned about the negative review regarding this plugin. Is this right?

    Posted: 1 year ago #
  3. BarLuc
    Member

    12345

    I like this idea too and I like to see this feature .

    Posted: 1 year ago #
  4. Staubsauger
    Member

    Yes, I'm waiting for this too.

    Posted: 11 months ago #
  5. criclover
    Member

    12345

    I've rated it 5 by 5 stars . It's a good idea because Category had no different perimeters to control different posts of different categories individually

    Posted: 11 months ago #
  6. Absolutely love the idea. Hopefully it will be changed.

    Posted: 9 months ago #
  7. haittamaa
    Member

    Put this code in functions.php or your own plugin:

    add_action( 'pre_get_posts', 'posts_per_category' );
    function posts_per_category( $query ) {
    	if($query->get( 'posts_per_category' )){
    		$origin_query = $query->query;
    		unset($origin_query['cat']);
    		unset($origin_query['posts_per_category']);
    		if($query->get('cat')){
    			$cats = explode(',', $query->get('cat'));
    			$ids = array();
    			foreach($cats as $cat){
    				$args = $origin_query;
    				$args['cat'] = $cat;
    				$args['fields'] = 'ids';
    				$args['posts_per_page'] = $query->get( 'posts_per_category' );
    				$q = new WP_Query($args);
    				if(isset($q->posts) && !empty($q->posts)){
    					foreach((array) $q->posts as $id) {
    						$ids[] = $id;
    					}
    				}
    				wp_reset_postdata();
    			}
    			$query->set('post__in', $ids);
    		}
    	}
    }

    use it like this:

    $query = new WP_Query("cat=1,2,3&posts_per_category=2");

    Posted: 6 months ago #
  8. tscoke
    Member

    Thanks haittamaa - that worked perfect! I placed the function in a child theme functions.php file and then duplicated the parent theme folder structure and placed a duplicate copy of the respective theme file in the child directory. Works great!

    Posted: 4 months ago #
  9. @haittamaa:

    Thanks for your effort! I tried this Code Snippet and it is working like a charm! Will probably use it in a widget.

    Thanks again!

    Posted: 4 months ago #
  10. tscoke
    Member

    One follow-up - is there some code I can add to that same function that will also order the categories by name(slug)?

    Posted: 4 months ago #

RSS feed for this topic

Reply »

You must log in to post.

  • Rating

    12345
    59 Votes
  • Status

    This is plugin territory