0

When user open any post, then on the right side they can see related posts to that post. But currently in related posts my current open post also showing, how i can exclude that post which is currently open.

2 Answers 2

3

Use the parameter 'post__not_in' to exclude post IDs:

$posts = new WP_Query(
    array (
        'post__not_in' => array(get_the_ID()) // exclude current post ID
    )
);
1
  • 1
    Use the source in a plugin, about the hook pre_get_posts is sure the best way.
    – bueltge
    Mar 13, 2013 at 11:41
1

If you could give us some code snippets of what you are currently using, it would help us formulate an answer. Unfortunately I don't have enough reputation to say this as a comment on the OP, so I will provide my answer based on the knowledge provided in the OP.

When loading the current post (presumably by using single.php), you can save the post ID in a PHP variable, like so:

<?php $do_not_duplicate = $post->ID; ?>

Later, in your loop to display related posts, you need an if-statement to skip the loop if the ID's match. Like so:

<?php
    // Get related posts
    $related = new WP_Query( $args );
    while ( $related->have_posts() ) : $related->the_post();
        if (in_array($post->ID, $do_not_duplicate)) continue;
?>
<!-- Your html for related post listing -->
<?php 
    endwhile;           // End 'while have_posts()'
    wp_reset_postdata();    // Reset Post Data
?>
6
  • <?php $args=array( 'category_name' => $catname, 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 12, 'caller_get_posts'=> 1 ); $my_query = null; $my_query = new WP_Query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?>
    – Adi
    Mar 13, 2013 at 11:16
  • @Adi Please(!) always update/edit your question with additional information. Don't write comments for that. A comment should be "Hey, I added the info :)" or similar.
    – kaiser
    Mar 13, 2013 at 12:13
  • @MarcDingena If you need clarification of the question, please leave a comment at the question requesting additional Info. Thanks.
    – kaiser
    Mar 13, 2013 at 12:14
  • @kaiser next time i be carefull about that. But i want to know one thing how i make my code in a block. The short code provide is not working in my comments. See my above commment how it look.
    – Adi
    Mar 13, 2013 at 12:18
  • @kaiser I can't do that because I don't have 50 reputation yet. Mar 13, 2013 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.