list wordpress posts from current category only

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.

Read More

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>

Related posts

Leave a Reply

5 comments

  1. 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>
    
  2. <!--Insted Of this-->
    $myposts = get_posts('numberposts=5&category=1');
    <!--Use This-->
    $cat_ID = get_query_var('cat');
    query_posts('cat='.$cat_ID.'&showposts=5&order=ASC');
    
  3. $args=array(
    'cat' => get_query_var('cat'),
      'orderby' => 'title',
      'order' => 'ASC',
      'posts_per_page'=>-1,
      'caller_get_posts'=>1
    );
    $my_query = new WP_Query($args);
    

    It worked for me!

  4. So I found this bit of code which works great in showing all posts in the current category.

     <ul id="catnav">
    
     <?php
    foreach( ( get_the_category() ) as $category ) {
    $the_query = new WP_Query('category_name=' . $category->category_nicename . '&showposts=5&order=ASC');
    while ($the_query->have_posts()) : $the_query->the_post();
    ?>
                <li>
                    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
                </li>
    <?php endwhile; ?>
    <?php
    }
    ?>
    
    
    </ul>
    

    But I have several categories I wish to exclude.
    Some posts exist in two categories I want to exclude showing the post in categories 8,9 and 11.

    Any ideas?

  5. I think it is better to get posts from category id instead of category name
    so that you can write an if else condition and you can exclude the posts which are having the id as 8,9,11