• Resolved tpalombo

    (@tpalombo)


    I would like to display all of the posts within the current category on my sidebar, ideally by automatically detecting the current category.

    The following code lists all categories and then the child posts. How can I limit this to only the current category?

    <?php
    //get all children of category "Site Articles", then display posts in each cat
    $taxonomy = 'category';
    $param_type = 'category__in';
    $cat_id = get_cat_ID('Site Articles');
    $term_args=array(
      'orderby' => 'name',
      'order' => 'ASC',
      'child_of' => $cat_id
    );
    $terms = get_terms($taxonomy,$term_args);
    if ($terms) {
      foreach( $terms as $term ) {
        $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() ) {
          echo 'List of Posts in '.$taxonomy .' '.$term->name;
          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().
    ?>
Viewing 3 replies - 1 through 3 (of 3 total)
  • You need to modify this bit:

    $cat_id = get_cat_ID(‘Site Articles’);

    If this code is outside the loop then change it to something like

    global $post;
    $categories = get_the_category($post->ID);
    $cat_id = $categories[0]->cat_ID;

    http://codex.wordpress.org/Function_Reference/get_the_category
    may give you some ideas

    Simon

    Thread Starter tpalombo

    (@tpalombo)

    Thanks Simon, unfortunately that didn’t work. It stopped outputting the list of posts.

    This is all running outside of the loop – and in place of the loop.

    Any other ideas? Your help is appreciated.

    Tony

    Thread Starter tpalombo

    (@tpalombo)

    I found a solution:

    The following works perfectly:

    <?php
    global $post;
    $categories = get_the_category();
    $category = $categories[0];
    $cat_ID = $category->cat_ID;
    
    $myposts = get_posts("numberposts=20&category=$cat_ID");
    ?>
    
    <?php foreach($myposts as $post) :?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php endforeach; ?>
Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Detect current Category and List Child Cat Posts’ is closed to new replies.