WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Category-specific sidebar (4 posts)

  1. cutout
    Member
    Posted 6 years ago #

    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?

  2. Kafkaesqui

    Posted 6 years ago #

    <?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 ; ?>
  3. cutout
    Member
    Posted 6 years ago #

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

  4. schikowski
    Member
    Posted 5 years ago #

    Kafkaesqui,
    You rock.
    Thank you.

Topic Closed

This topic has been closed to new replies.

About this Topic