在循环内列出 post 类别的数组

List array of post's categories inside loop

我有 post 的列表显示为网格,我需要每个 post 列出自己的类别,用逗号分隔。 我有一个功能代码,但它只列出了一个类别。

当前代码:

   <?php $the_query = new WP_Query(array('post_type' => 'attachment', 'category_name' => 'category')); 

   while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <?php $category = get_the_category();
          echo '<figure data-groups='. esc_attr('["'.$category[0]->slug.'"]').'>';
          echo'<img src="'.wp_get_attachment_url ('medium').'"/>';
          </figure>';?>
       <?php endwhile; wp_reset_postdata();?> 

输出<figure data-groups='["category1"]>

我需要的是<figure data-groups='["category1","category2","category3"]>

我确实看到了一个类似的问题 here,但我无法在没有错误 "Cannot use object of type WP_Term as array." 的情况下正常工作 这是我产生错误的尝试:

  $categories = get_the_category();
    $category_names = array();
    foreach ($categories as $category)
    {
        $category_names[] = $category->cat_name;
    }
    echo implode(', ', $category_names);

          echo '<figure class="gallery-photo" data-groups='. esc_attr('["all","'.$category_names.'"]').'>';

我猜我将不得不使用某种功能。非常感谢我能得到的任何帮助! 编辑 - 最终代码:

 <?php $the_query = new WP_Query(array('post_type' => 'attachment', 'category_name' => 'category')); 
 while ( $the_query->have_posts() ) : $the_query->the_post();

    $categories = get_the_category();
    $category_names = array();
    foreach ($categories as $category){
      $category_names[] = $category->slug; }
      $category_list = implode("\",\"",  $category_names);

    echo '<figure data-groups='. esc_attr('["'.$category_list.'"]').'>';
          echo'<img src="'.wp_get_attachment_url ('medium').'"/>';
          </figure>'; endwhile; wp_reset_postdata();?> 

正如您在复制的代码中看到的那样,$category_names 是一个数组。您不能按照您的方式 echo 数组来获得此输出:

<figure data-groups='["category1","category2","category3"]'>

尝试:

echo "<figure data-groups='[ " . "\"" . implode( "\",\"", $category_names ) . "\"" . " ]'>";
// outputs
// <figure data-groups='[ "sample","Uncategorised" ]'>