我想知道是否可以在wp_query中显示粘贴帖子并根据各自的类别对其进行排序:
loop(
- the first sticky post has the category 1
- the second sticky post has the category 2
- the third sticky post has the category 1
)
应显示:
- category 1:
- the first sticky post
- the third sticky post
- category 2:
the second sticky post
使用这个html:
<div class="flex-6">
<h4><?php
$category = get_the_category();
echo $category[0]->cat_name;
?></h4>
<ul class="list">
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
</ul>
</div>
我有粘贴帖子的正确循环:
$sticky = get_option('sticky_posts');
$query = new WP_Query(array('post__in' => $sticky));
if($query->have_posts()) : while($query->have_posts()) : $query->the_post();
$category_name = get_the_category();
$category_name = $category_name[0]->cat_name;
endwhile; endif;
获得最终结果
<div class="flex-6">
<h4>Category 1</h4>
<ul class="list">
<li><a href="the_first_link">The first title</a></li>
<li><a href="the_third_link">The third title</a></li>
</ul>
</div>
<div class="flex-6">
<h4>Category 2</h4>
<ul class="list">
<li><a href="the_second_link">The secondtitle</a></li>
</ul>
</div>
任何想法? 谢谢你的时间
答案 0 :(得分:1)
最直接的方法是首先获得类别:
<?php
$cat_args = array(
'child_of' => 0,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'taxonomy' => 'category'
);
$cats = get_categories($cat_args);
然后循环播放帖子:
$sticky = get_option('sticky_posts');
foreach ($cats as $cat) :
$args = array(
'post_type' => 'post',
'post__in' => $sticky,
'posts_per_page' => -1,
'orderby' => 'title', // or whatever you want
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $cat->slug
)
)
);
$posts = get_posts($args);
if ($posts) :
?>
<div class="flex-6">
<h4><?php echo $cat->cat_name; ?></h4>
<ul class="list">
<?php foreach ($posts as $post) : ?>
<li><a href="<?php echo get_permalink($post->ID); ?>"><?php echo get_the_title($post->ID); ?></a></li>
<?php endforeach; ?>
</ul>
</div>
<?php
endif;
endforeach;