如何在wordpress中只显示每个类别的两篇文章?
问题描述:
我必须从每个类别显示2个职位。下面的代码获取属于每个类别的所有帖子。我的结构是基于标签的。我附上了我设计的图像。我的标签包含“所有的(显示所有岗位)”,“症状(表明相关症状职位只”等,点击每个选项卡显示相关的帖子。 如何在wordpress中只显示每个类别的两篇文章?
<?php $recent = new WP_Query("post_type=post&posts_per_page=-1&orderby=date&order=DESC");
$count=0;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
while($recent->have_posts()) : $recent->the_post(); ?>
<?php $c = get_the_category();
$cat = $c[0]->cat_name;
$slug = $c[0]->category_nicename;
?>
<div class="element-item transition <?php echo $slug;?>" data-category="<?php echo $slug;?>">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<div class="descrip">
<h2><?php the_title(); ?></h2>
</div>
</a>
</div>
<?php endwhile; wp_reset_postdata(); ?>
[![请在此输入图片说明] [2] [2]
任何帮助,将不胜感激
答
尝试这样
<?php
$cat_args = array(
'orderby' => 'date',
'order' => 'DESC',
'child_of' => 0,
'parent' => '',
'type' => 'post',
'hide_empty' => true,
'taxonomy' => 'category',
);
$categories = get_categories($cat_args);
foreach ($categories as $category) {
$query_args = array(
'post_type' => 'post',
'category_name' => $category->slug,
'posts_per_page' => 2,
'orderby' => 'date',
'order' => 'DESC'
);
$recent = new WP_Query($query_args);
while($recent->have_posts()) :
$recent->the_post();
?>
<div class="element-item transition <?php echo $category->slug;?>" data-category="<?php echo $category->slug;?>">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<div class="descrip">
<h2><?php the_title(); ?></h2>
</div>
</a>
</div>
<?php endwhile;
}
wp_reset_postdata();
?>
首先列出所有的类别,然后在foreach
循环遍历每个,并且只查询2个最近的。
请注意,您可以通过这种方式列出任何分类。我只是把
'taxonomy' => 'category',
但这可以是分配给您的自定义帖子类型的分类,例如。论据
列表看起来有点像这样:
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'category',
'pad_counts' => false
);
希望这有助于。