• Resolved Darren

    (@cutout)


    This will hopefully be simple — in the sidebar of each single-post page, I want a box which says, “More from this category” and lists the last 5 relevant headlines from whatever category you’re in. I realize I can specify an ID and do it like this:

    <?php if ( is_single() || in_category('3') ) : ?>
    <li>
    <h2>More in this Section</h2>
    <ul class="bullets">
    <?php
    $posts = get_posts('numberposts=10&category=3');
    foreach($posts as $post) :
    ?>
    <li>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
    <?php endforeach; ?>
    </ul>
    </li>
    <?php endif ; ?>

    But, I don’t want to manually type in the ID# for each. How can I use the code above and make it more dynamic?

Viewing 3 replies - 1 through 3 (of 3 total)
  • <?php
    if ( is_single() ) :
    global $post;
    $category = get_the_category();
    ?>
    <li><h2>More in this Section</h2>
    <ul class="bullets">
    <?php
    $posts = get_posts('numberposts=10&category='. $category[0]->term_id);
    foreach($posts as $post) :
    ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>
    </ul>
    </li>
    <?php endif ; ?>

    This collects all categories a post is assigned to and passes the category ID# of the first category ($category[0]->term_id) as the value for the get_posts() ‘category’ parameter.

    (Using WordPress <= 2.2.x, change $category[0]->term_id
    to $category[0]->cat_ID)

    Also, for multiple categories (because someone *will* ask):

    <?php
    if ( is_single() ) :
    global $post;
    $categories = get_the_category();
    foreach ($categories as $category) :
    ?>
    <li><h2>More in <?php echo $category->name; ?></h2>
    <ul class="bullets">
    <?php
    $posts = get_posts('numberposts=5&category='. $category->term_id);
    foreach($posts as $post) :
    ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>
    </ul>
    </li>
    <?php endforeach; endif ; ?>
    Thread Starter Darren

    (@cutout)

    Brilliant, Kafkaesqui, thank you! I will test that code tonight.

    Kafkaesqui,
    You rock.
    Thank you.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Category-specific sidebar’ is closed to new replies.