views:

82

answers:

1

i have 4 posts belonging to "news" category. I've added a this code in single.php to show the title of other posts in the same category in the sidebar.

<?php
    $query = "showposts=10&orderby=rand&cat=";      
    foreach((get_the_category()) as $category) { 
    $query .= $category->cat_ID .","; 
    }       
    query_posts($query);
?>
<ul class="related grid_5">
    <?php while (have_posts()) : the_post(); ?>
        <li><?php the_title() ?></li>
     <?php endwhile; ?>      
</ul>

using this i can retrieve all posts in the same category and display them and all 4 titles belonging to "news" are displayed in the widget. but I'm on post#3 how can show only #1, #2, and #4 titles in the widget?

+1  A: 

If you captured the ID of your currently displayed post, you could add a conditional check to avoid displaying it in the while loop.

1. Get ID of current post

I'm assuming you're outside the loop as you're in your sidebar, so you could get the current post ID like so:

global $wp_query;
$currentPost = $wp_query->post->ID;

However, if you are in the loop, the following will work:

global $post;
$currentPost = $post->ID;

2. Skip printing of current post's title

Once you've got the current post's ID, skipping the print is pretty straightforward:

<ul class="related grid_5">
    <?php while (have_posts()) : the_post(); 
        if( $post->ID != $currentPost ) ?>
            <li><?php the_title() ?></li>
    <?php endwhile; ?>      
</ul>
Pat