Foreach in a foreach and filtering through both of them

I am trying show related posts through posts linked through a category in wordpress but I am having trouble filtering the results.

Here is my code at the moment:

Read More
     $current_post = $post->ID;
         $i = 0;
         $categories = get_the_category();
         foreach ($categories as $category) {            
            $posts = get_posts('numberposts=4&category='. $category->term_id . '&exclude=' . $post->ID);
                foreach($posts as $post) { 
                                     // DO BASIC ECHO POST CONTENT STUFF

                     $i++;
                     if ($i == 3) break;
                         }
           } 


wp_reset_query();

The problem with my code is that when a post is in 3 categories (even if that isn’t good web practise) this loop echo’s 12 posts (4 posts per category) and if a different article is in the same 3 categories, it is shown 3 times (duplicated). I want to show MAX 4 posts, and have no duplicates.

I thought the $i == 3 break; would make it stop after the first ‘global’ 4 results. But it doesn’t? and how can I make it so there are no duplicate results in the results?

Related posts

Leave a Reply

2 comments

  1. You can create array of shown posts and then check if post not in this array show it.

    $show_array = array();
    
    // ...
    
    foreach($posts as $post) { 
       if (!in_array($post['id'], $show_array)) {
           // show post
           $show_array[] = $post['id'];
       }
    }
    
  2. $current_post = $post->ID;
             $i = 0;
             $categories = get_the_category();
             foreach ($categories as $category) {            
                $posts = get_posts('numberposts=4&category='. $category->term_id . '&exclude=' . $post->ID);
                    foreach($posts as $post) { 
                                         // DO BASIC ECHO POST CONTENT STUFF
    
                         $i++;
                         if ($i == 3) break 2;
                             }
               } 
    

    wp_reset_query();