Forums

[resolved] Use WP_Query to make nested list of posts (by date) in category (by name) (3 posts)

  1. SubjectEgo
    Member
    Posted 3 years ago #

    I need to use WP_Query to loop through each category and list all posts in each category. Each category list would be an item in a larger list. As a note, when I say "list", that is not necessarily the formatting that the posts will displayed with when they are retrieved. It will more than likely be divs.

    Categories must be listed in alphabetical order. Posts must be listed by date (most recent first) of revision, not publication. I must have the option to get additional data with each post, such as tags, excerpt, custom fields, etc.

    What's the best way to do this?

  2. MichaelH
    Volunteer
    Posted 3 years ago #

    Get categories, print posts within each category

    <?php
    $categories=get_categories('orderby=name&order=ASC');
      foreach($categories as $category) {
          $posts=get_posts('showposts=-1&cat='. $category->term_id);
          if ($posts) {
            echo 'Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>
     ';
            foreach($posts as $post) {
              setup_postdata($post); ?>
              <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
    
              <?php
            } // foreach($posts
          } // if ($posts
        } // foreach($categories
    ?>

    Related:
    the_excerpt(),
    the tags()
    Using Custom Fields

    If necessary to display tags may need this in your loop:

    global $wp_query;
    $wp_query->in_the_loop = true;
    the_tags();
  3. SubjectEgo
    Member
    Posted 3 years ago #

    That did the trick! Thank you for your time.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags