我有一些帖子不止一个类别。在post循环中,我根据用户选择的类别获取帖子。如果用户选择了两个类别,其中一篇文章被分配给这两个类别,则循环将复制该文章。我试着用array_unique()
但不起作用。
这是我的代码:
<?php
global $current_user;
get_currentuserinfo();
//$current_user->user_categories;
$ucategory = maybe_unserialize($current_user->user_categories);
foreach ($ucategory as $category) {
$query = new WP_Query( array( \'post_type\' => array( \'service\'),
\'category__in\' => array($category)));
$i=0;
while ( $query->have_posts() ) : $query->the_post();
if ($i%3==0) echo \'
\';
echo \'
<div class="col-md-4 ">
<div class="col-md-12 service-cell">
<a href="\'; the_permalink(); echo \'">\';
echo the_post_thumbnail(\'thumbnail\', array(\'class\' => \'app-icon\'));
echo \'<h2 class="center">\'; the_title(); echo \'</h2></a>\';
foreach((get_the_category()) as $childcat) {
if (cat_is_ancestor_of(3, $childcat)) {
echo \'<h3 class="sub">\';
echo $childcat->cat_name . \'</h3>\';
}}
echo \'<p>\';
echo excerpt(25);
echo \'<p><a href="\'; the_permalink(); echo \'">\'; echo \'Wijzig uw gegevens</a>
<a class="pull-right"><span class="label label-default"><span class="glyphicon glyphicon-ok"></span></span></a></p>\';
echo \'</p>\';
echo \'\';
echo \'</div></div>\';
if ($i%3==2) echo \'\';
$i++;
endwhile;
}
?>
最合适的回答,由SO网友:TheDeadMedic 整理而成
您不需要对每个类别进行循环&;逐个查询,只需查询一次:
$query = new WP_Query(
array(
\'post_type\' => array( \'service\' ),
\'category__in\' => $ucategory,
\'posts_per_page\' => -1,
)
);