WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Sort Posts by Category (6 posts)

  1. gcarson
    Member
    Posted 4 years ago #

    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.

  2. vtxyzzy
    Member
    Posted 4 years ago #

    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;
    }
    
    ?>
  3. gcarson
    Member
    Posted 4 years ago #

    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");

  4. vtxyzzy
    Member
    Posted 4 years ago #

    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;
    }
    
    ?>
  5. gcarson
    Member
    Posted 4 years ago #

    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!

  6. vtxyzzy
    Member
    Posted 4 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.