0

I want sort posts in the loop by category and before first post in each category display category name.

For example:

Category 1
   Post
   Post
   Post
Category 2
   Post
   Post
   Post
   Post
Category 3
   Post

etc.

Is it possible to do this using one loop?

p.s. sorry for my terrible english.

0

You can go with two queries, the first to get your taxonomies like this :

$categories = get_categories();

More infos about the params here. And then browse your category collections and get the first n posts of it like this :

foreach($categories as $cat)
{
    //get the $n posts from this category
    $post_query = new WP_Query(
        array('post_type' => 'post',
          'posts_per_page' => $n ,
          'tax_query' => array(
                array(
                  'taxonomy' => $cat->taxonomy,
                  'field'    => 'slug',
                  'terms'    => $cat->term_id,
               )
         )
       )
    );
    echo '<h2>'.$cat->name.'</h2>';
    while($post_query->have_posts()){
       $post_query->the_post();
       echo get_the_title();
    }wp_reset_query();
}

Hope it will help =)

  • 1
    Just note, your approach works, but is really expensive and you can run into queries timing out with large amount of posts and categories. :-) – Pieter Goosen Apr 28 '15 at 15:26
  • Totally agree, I'm reading the link you posted as a comment to learn the "clean approach", but in most of cases it's the fastest way to get things done on a small website in my opinion. – Sladix Apr 28 '15 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.