Take the 2-minute tour ×

I have a custom post type for accessories. When you view the post it also shows related posts. It looks great, but it also shows the current post within related posts.

Is there a way to exclude the current post from the loop?

    $category = get_the_category(); 
    $model = $category[1]->cat_name;
    $accessory = array('numberposts' => 8, 'offset'=> 1, 'post_type' => 'accessory', 'category_name' => $model, 'order' => 'DESC');
    query_posts( $accessory );
      <?php if (have_posts()) : ?>
            <?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'openeye' ), 'after' => '</div>' ) ); ?>
            Part Number: <?php echo get_post_meta($post->ID, "accessory-part-number", true); ?>
            <?php $desc = get_post_meta($post->ID, "accessory-description", true); ?>
            <p><?php echo utf8_truncate( $desc ); ?></p>
            <a href="<?php echo get_permalink(); ?>">Learn more about the <?php the_title(); ?></a>
        <?php endwhile; ?>
      <?php endif; ?>
share|improve this question

2 Answers 2

up vote 3 down vote accepted

Try this:

For your single-accessory.php template:


      // excludes this post from 'Related posts' in the sidebar
      $GLOBALS['current_id'] = $post->ID; 


For your sidebar or where you want to show related posts:

        if (is_singular('accessory') ) :
        global $post;
        $categories = get_the_category();
            $exclude = $GLOBALS['current_id'];
        $args = array(
        'post_type' => 'accessory',
        'post__not_in' => array($exclude),
        'posts_per_page' => -1

        foreach ($categories as $category) :
        $posts = get_posts($args);

        if(count($posts) > 1) {

                 //do stuff
share|improve this answer

First, you should never use query_posts() for secondary Loops.

As for excluding current post, it would take something like this in arguments:

'post__not_in` => array( get_the_ID() )
share|improve this answer
Totally make sense, thx! What's odd though is that each returns entirely different results. Is there something else I need to know or do regarding querys? –  Zach Shallbetter Mar 21 '11 at 23:13
@Zach Shallbetter I am not sure what each and how different, could you please rephrase that or add examples to original question? –  Rarst Mar 21 '11 at 23:18
Sure, WP_Query returns no results. Get_Posts returns one result and of course query_posts returns everything. –  Zach Shallbetter Mar 21 '11 at 23:23
@Zach Shallbetter I have no idea what to think of that. query_posts() and get_posts() are essentially just calls to WP_Query. –  Rarst Mar 22 '11 at 8:43
Wild, I'm obviously doing something incorrect then. –  Zach Shallbetter Mar 22 '11 at 15:46

Your Answer


