Forums

Post List by Category (2 posts)

  1. jannmirch
    Member
    Posted 2 years ago #

    I've found a lot of code and widgets that come close, but none that do what I want.

    I have 3 categories with multiple posts within each. I want the sidebar to show the categories regardless of which page I'm on AND show the posts but only for my current category.

    So if I'm on a post for category 1 my sidebar would look like:

    Category1
    - post 1
    - post 2

    Category2

    Category3

    If I'm on a post for category 2 my sidebar would look like:
    Category1

    Category2
    - post 1
    - post 2

    Category3

    Can't quite get there. Any help would be appreciated.

  2. MichaelH
    Volunteer
    Posted 2 years ago #

    <?php
    //get all categories, then display category title and if category is the current queried category display post titles for that category
    if (is_category( )) {
      $current_cat = get_query_var('cat');
      $taxonomy = 'category';
      $param_type = 'category__in';
      $term_args=array(
        'orderby' => 'name',
        'order' => 'ASC',
      );
      $terms = get_terms($taxonomy,$term_args);
      if ($terms) {
        foreach( $terms as $term ) {
          echo '<p>' . $term->name . '<p>';
          if ($current_cat == $term->term_id ) {
            $args=array(
            "$param_type" => array($term->term_id),
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'caller_get_posts'=> 1
            );
            $my_query = null;
            $my_query = new WP_Query($args);
            if( $my_query->have_posts() ) {
              while ($my_query->have_posts()) : $my_query->the_post(); ?>
                <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
               <?php
              endwhile;
            }
          }
        }
      }
      wp_reset_query();  // Restore global post data stomped by the_post().
    }
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic