2

I'm running a query to dig up related posts based on tags. If CURRENT POST has tags A, B and C, show 3 more posts that have either A, B or C tags. I also only show posts that are 365 days old or newer.

$date_to_compare = date('F jS, Y', strtotime('-365 days')); 
$new_category = get_the_category();
$the_tags = get_the_tags();
$first_tag = $the_tags[0]->term_id;
$second_tag = $the_tags[1]->term_id;
$this_post2 = get_the_ID();
   $args2 = array(
    'posts_per_page' => 3,
    'post_type' => 'post',
    'ignore_sticky_posts' => 1,
    'orderby' => 'rand',
    'tag__in' => array( $first_tag, $second_tag ),
    'exclude' => $this_post2,
    'date_query' => array(
        array(
            'after'     => $date_to_compare,
            'inclusive' => true,
        ),
    ),
  );
  $the_query_2 = new WP_Query( $args2 );
  if ($the_query_2->have_posts()) :
  while ( $the_query_2->have_posts() ) : $related_post_count++;
    $the_query_2->the_post(); ?>
  // show the post content
  endwhile; endif;

This usually works really well, but there's one case where CURRENT POST is one of only 3 posts that would match this. In that event, CURRENT POST is included in the three related posts, despite $this_post2 = get_the_ID(); and 'exclude' => $this_post2,

Thus, my conundrum.

2
  • 1
    Oh man [smacks head] that was exactly it. The proper argument is 'post__not_in'
    – Nathan
    Aug 26, 2016 at 18:32
  • It happens! Hope it works for you.
    – jdm2112
    Aug 26, 2016 at 18:33

1 Answer 1

1

WP_Query does not support an exclude argument. To exclude a post by ID, use post__not_in and pass it an array of IDs.

Using your code above, your arguments could look like this:

$args2 = array(
    'posts_per_page' => 3,
    'post_type' => 'post',
    'ignore_sticky_posts' => 1,
    'orderby' => 'rand',
    'tag__in' => array( $first_tag, $second_tag ),
    'post__not_in' => array( $this_post2 ),
    'date_query' => array(
        array(
            'after'     => $date_to_compare,
            'inclusive' => true,
        ),
    ),
);

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.