• Resolved gcarson

    (@gcarson)


    I have my tags in one of three categories. I would like to sort the posts first by category then by date. So all of category A, newest to oldest, then category B, newest to oldest and so on. I was thinking I need three separate loops, but I’m not certain how to do it or what might be the best way? Do I need three different loops? Or can I somehow do it with one loop and do some sorting in the loop?

    I’ve tried adding

    <?php rewind_posts('category_name=cat_name'); ?>
    <?php while (have_posts()) : the_post(); ?>

    before my loop but that didn’t show posts only from ‘cat_name’ so I’m sort of stuck.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Here is an abbreviated version of what I think you want. It only shows the category name followed by the post titles as links, but you should be able to use it as a guide.

    <?php
    foreach (array('First Category','Odd Pages','Even Posts') as $catname) {
       $catid = get_cat_id($catname);
       $myquery = new WP_Query("cat=$catid");
       if ($myquery->have_posts()) :
          echo "<h2>Posts for Category $catname</h2>";
          while ($myquery->have_posts()) : $myquery->the_post(); ?>
             <p><a>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
          <?php endwhile;
       endif;
    }
    
    ?>
    Thread Starter gcarson

    (@gcarson)

    OK this almost does everything I need. This is only going on my ‘tag’ archive page. So I only want to pull posts in say Tag1, then sort by my three categories. Trying to figure out how to add that to $myquery = new WP_Query(“cat=$catid”);

    This should do what you want:

    <?php
    global $query_string;
    $my_query_string = $query_string;
    foreach (array('First Category','Odd Pages','Even Posts') as $catname) {
       $catid = get_cat_id($catname);
       $myquery = new WP_Query($my_query_string . "&cat=$catid");
       if ($myquery->have_posts()) :
          echo "<h2>Posts for Category $catname</h2>";
          while ($myquery->have_posts()) : $myquery->the_post(); ?>
             <p><a>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
          <?php endwhile;
       endif;
    }
    
    ?>
    Thread Starter gcarson

    (@gcarson)

    If I could kiss you, I would! Works perfect. This code may come in handy for others like me who use WordPress as a CMS. Thank you so much!

    You are welcome! Now, please use the dropdown at top right to mark this topic ‘Resolved’.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Sort Posts by Category’ is closed to new replies.