WordPress.org

Forums

Another Single Category Question (7 posts)

  1. TonySt
    Member
    Posted 9 years ago #

    I'd like to add a little loop on a sidebar in a new theme I'm making. I'd like the loop to ONLY display posts from category number two. Any suggestions?

  2. moshu
    Member
    Posted 9 years ago #

  3. TonySt
    Member
    Posted 9 years ago #

    ...Nice refrerences, but the codex confuses me more than anything else.

    If someone familiar on the topic could give me some code to do the aforementioned task, I'd be quite happy indeed ;-)

  4. sadish
    Member
    Posted 9 years ago #

    try this.

    <?php $posts = query_posts("cat=2")?>
    <?php if ($posts) : foreach ($posts as $post) : start_wp(); ?>
    <div class="post">
    <h2 class="post-title"><?php comments_popup_link('(0)', '(1)', '(%)','',''); ?>< a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></h2>
    <div class="post-content">
    <?php the_content(''); ?>
    </div>
    </div>
    <?php endforeach; else: ?>
    <?php _e('Sorry, no posts matched your criteria.'); ?>
    <?php endif; ?>

    Thanks
    Sadish

  5. sadish
    Member
    Posted 9 years ago #

    i put a space between '<' and 'a' , otherwise, this forum makes it a hyperlink.
    you may have to remove the space.

    Thanks

  6. TonySt
    Member
    Posted 9 years ago #

    Well, I've got good news and I've got bad news..

    The good news? It worked! The bad news? My home page is now showing no posts. Crap.

  7. Kafkaesqui

    Posted 9 years ago #

    Replace the first part of sadish's code above (before the <div>) with this:

    <?php $cat_posts = new WP_Query("cat=2")?>
    <?php if ($cat_posts->have_posts()) : while($cat_posts->have_posts()) : $cat_posts->the_post(); ?>

    Then change this line:

    <?php endforeach; else: ?>

    to:

    <?php endwhile; else: ?>

    In fact, here's a simpler version that leaves off a few elements -- for example, we'll assume there are always posts in the category and not bother with the "sorry" message:

    http://pastebin.co.uk/600

    Also, if you need to limit the # of posts displayed, add a 'showposts' to your query:

    WP_Query('cat=2&showposts=5')

Topic Closed

This topic has been closed to new replies.

About this Topic