显示粘性帖子,并根据其类别进行分类


Show sticky posts and sort them out according to their category

我想知道是否可以在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>

有什么想法吗?感谢您抽出时间

最直接的方法是首先获取类别:

<?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;