0

I'm trying to add a related posts section to the bottom of my single post views. It needs to grab the categories of the current post and show just 2 posts that match any of those categories. I'm almost there, but my results are showing 2 from each category as opposed to a total of 2.

<?php if ( is_single() ) { ?>
    <div class="related-posts wrapper clearfix">
        <?php $categories = get_the_category();
            foreach ($categories as $category) {
                $cat = $category->cat_ID;
                $args=array(
                    'cat' => $cat,
                    'order' =>DESC,
                    'post__not_in' => array($post->ID),
                    'posts_per_page'=>2,
                );
            $my_query = null;
            $my_query = new WP_Query($args);
            if( $my_query->have_posts() ) {
                $i = 0; while ($my_query->have_posts() && $i < 3) : $my_query->the_post(); ?>
                    <h2 class="related-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                <?php  $i++; endwhile; }
            }
            wp_reset_query();
        ?>
    </div>
<?php } else {};?>  
4

Build an array of categories:

foreach ($categories as $category) {
    $cat[] = $category->cat_ID;
}

Then pass that to the query:

$args=array(
  'category__in' => $cat, 
  'order' =>DESC, 
  'post__not_in' => array($post->ID),
  'posts_per_page'=>2, 
);

In other words, put the query after the foreach, not inside of it.

0

$i is being reset for each category.

Try declaring $i before the foreach cat loop:

<?php 
$i = 0; 
$categories = get_the_category();
// etc

And if $i = 0, then you will get 3 posts before it stops, so try this:

if( $my_query->have_posts() ) {
      while ($my_query->have_posts() && $i < 2)
      // etc

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.