2

我正在尝试通过通过 wordpress 中的类别链接的帖子显示相关帖子,但我无法过滤结果。

这是我目前的代码:

     $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();

我的代码的问题是,当一个帖子属于 3 个类别时(即使这不是很好的网络实践),这个循环会回显 12 个帖子(每个类别 4 个帖子),如果另一篇文章属于相同的 3 个类别,它是显示 3 次(重复)。我想显示 MAX 4 个帖子,并且没有重复。

我以为 $i == 3 break; 将使其在第一个“全局”4 个结果之后停止。但它没有?我怎样才能做到这一点,所以结果中没有重复的结果?

4

2 回答 2

1

您可以创建显示帖子的数组,然后检查帖子是否不在此数组中显示。

$show_array = array();

// ...

foreach($posts as $post) { 
   if (!in_array($post['id'], $show_array)) {
       // show post
       $show_array[] = $post['id'];
   }
}
于 2013-02-01T09:40:26.897 回答
0
$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();

于 2013-02-01T15:17:33.493 回答