list wordpress posts from current category only

user1765225 picture user1765225 · Oct 22, 2012 · Viewed 21.1k times · Source

I'm attempting to create a second nav menu on my wordpress site.

I want this to show links to all posts within the current category only.

I've been experimenting with the get_posts function but am struggling to find how to dynamically select the current category. i.e. what to place in here category=x

Any help is greatly appreciated

Here is my template code I have been using

<ul id="catnav">

     <?php
     global $post;
     $myposts = get_posts('numberposts=5&category=1');
     foreach($myposts as $post) :
     ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
     <?php endforeach; ?>



    </ul>

Answer

user1765225 picture user1765225 · Oct 24, 2012

Finally solved it with this code from here: http://www.snilesh.com/resources/wordpress/wordpress-recent-posts-from-current-same-category/

Modified it to include current page and list ascending

<ul id="catnav">
<?php
global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;
$myposts = get_posts(array('numberposts' => 5, 'offset' => 0, 'category__in' => array($category), 'post_status'=>'publish', 'order'=>'ASC' ));
foreach($myposts as $post) :
setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a>
</li>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
<li><a href="?p=46">Why Us?</a></li>

</ul>