WordPress.org

Forums

[resolved] Get Posts: Category (6 posts)

  1. jonizen
    Member
    Posted 6 years ago #

    Hey guys,
    When looking at a post, I need it to bring up a list of only the posts in its category. Currently it lists all posts regardless of category.

    I've figured out how to make it static
    $postslist = get_posts('category_name=news');

    I need it to be dynamic.

    Here is my relevant code

    <ul>
      <?php
        $postslist = get_posts();
        foreach ($postslist as $post) :
        setup_postdata($post);
      ?> 
    
    <li>
       <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
    <?php endforeach; ?>
    </ul>

    [moderated--bump removed. Please refrain from bumping as per Forum Rules]

  2. MichaelH
    Member
    Posted 6 years ago #

    Something for in 'standard' loop?

    <?php $post_cats=wp_get_post_categories($post->ID);?>
    <ul>
    <?php
      $args=array(
        'showposts'=>4,
        'cat'=>$post_cats[0],
        'post__not_in' => array($post->ID)
      );
        $postslist = get_posts($args);
     if ($postslist) {
        foreach ($postslist as $mypost) :
        ?>
          <li>
          <a href="<?php echo get_permalink($mypost->ID); ?>"><?php echo $mypost->post_title; ?></a>
          </li>
        <?php endforeach;
      }
    ?>
    </ul>

    Note: might also look at similar/related posts type plugins:
    http://rmarsh.com/plugins/similar-posts/
    http://wordpress.org/extend/plugins/tags/related

  3. jonizen
    Member
    Posted 6 years ago #

    I can't seem to get this to work Michael. The result is a link to the first post.

    I need a way to find out the current category for the post, and then I need to run a loop grabbing the posts in the same category.

  4. MichaelH
    Member
    Posted 6 years ago #

    I need a way to find out the current category for the post

    That's this:

    <?php $post_cats=wp_get_post_categories($post->ID);?>

    and $post_cats[0] is the ID of the 1st category returned for the post (posts can have multiple categories)

  5. MichaelH
    Member
    Posted 6 years ago #

    Here's the index.php for use with the WordPress Default Theme:

    http://wordpress.pastebin.ca/1342102

  6. jonizen
    Member
    Posted 6 years ago #

    It works, thank you

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags