查询每个类别最多4篇帖子
问题描述:
我创建了custom post type
dishmenu
。有类别在我的dishmenu
像Special,Breakfast,Lunch,Dinner
。现在我想从每个类别获得最多4条记录(如果可用)。查询每个类别最多4篇帖子
这是我到目前为止已经试过:
<?php
$menucat = get_terms('menu_category');
foreach($menucat as $category){
$menuQuery = new WP_Query(array('post_type'=>'dishmenu','posts_per_page'=>4,'category_name'=>$category->slug));
if($menuQuery->have_posts()):
while($menuQuery->have_posts()): $menuQuery->the_post();
$price = json_decode(json_encode(get_post_meta($menuQuery->post->ID)),false);
echo '<div class="element-item '.$category->slug.' col-sm-6" data-category="'.$category->slug.'" >
<div class="dish-menu-item">
<div class="dish-border-circle">
<div class="dish-menu-left"></div>
</div>
<div class="dish-menu-body">
<h4>'.get_the_title().'<span class="pull-right"><span class="error-text">'.$price->Price[0].'</span><sub>$</sub></span></h4>
<p>'.get_the_content().'</p>
</div>
<div class="dish-menu-right text-center">
<p style="padding:2px; display:inline-block;"></p>
</div>
</div>
</div>';
endwhile;
wp_reset_postdata();
else:
echo '<div class="element-item '.$category->slug.' col-sm-6" data-category="'.$category->slug.'" >
No posts found in '.$category->slug.'
</div>';
endif;
}
?>
现在的问题是,每次else块已被执行。
答
您需要使用tax_query
查询在WP_Query
请检查下面的查询
$arg=array(
'post_type'=>'dishmenu',
'posts_per_page'=>4,
'tax_query' => array(
array('taxonomy' => 'menu_category',
'field' => 'slug',
'terms' => $category->slug,
'include_children' => true)
)
);
$menuQuery = new WP_Query($arg);
+0
感谢哥们!它的工作原理... :) –
+0
你是最受欢迎的。我很高兴它有帮助 –
您使用自定义分类的类别? –
是的。 'menu_category'是分类。 –
您需要在WP_Query中使用tax_query查询。请检查下面的答案 –