• Alright, this should be simple but I can’t figure it out.

    In my single.php , I want to exclude the post that is shown in the main content loop from the list of recent posts that is displayed in the sidebar.

    The (simplified) main content loop looks like this:

    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <div class="article" id="post-<?php the_ID(); ?>">
        <h2><?php the_title(); ?></h2>
        <div class="entry">
            <?php the_content('Read the rest of this post'); ?>
        </div>
    </div>
    <?php endwhile; ?>
    <?php else : ?>
    *removed to simplify*
    <?php endif; ?>

    So my thought was to grab the output of the_ID in a variable, $exclude_post. (I’m not honestly sure if I’m doing that part correctly.) With that idea, the code to generate the recent post list is:

    <span class="hidden"><?php global $exclude_post; $exclude_post = the_ID(); ?></span>
    <?php if(is_single()) { ?>
    <?php $recent_query = new WP_Query("p=-$exclude_post&showposts=5"); ?>
    <?php if ($recent_query->have_posts()) : ?>
    <h3>recent</h3>
    <?php echo $exclude_post; ?>
    <ul>
    <?php while ($recent_query->have_posts()) : $recent_query->the_post(); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endwhile; ?>
    </ul>
    <?php else : ?>
    <?php endif; ?>

    I get a list of the recent posts, but the echoed variable doesn’t output and the current post still shows up in the list.

    Any help is appreciated, thanks.

    Bonus points if the solution can exclude all of the posts being displayed by the main loop (so I could use it on more than just single.php).

Viewing 2 replies - 1 through 2 (of 2 total)
  • I can’t help you with all of it, but I had a problem with something else until I realized the_ID() doesn’t RETURN a value, it only PRINTS a value.

    I’m looking for same solution.

    Anyone knowns how to do it?

    Thanks in advance.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Exclude currently displayed post(s) from Recent Posts list’ is closed to new replies.