在循环内部列出帖子的类别列表

在循环内部列出帖子的类别列表

问题描述:

我有显示为网格的帖子列表,并且我需要每个帖子列出其自己的类别,用逗号分隔。我有一个功能代码,但它只列出了一个类别。在循环内部列出帖子的类别列表

当前代码:

<?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,但我无法得到这个工作没有了读取错误“不能使用WP_Term类型的对象作为数组。” 这里是我的尝试所产生的错误:

$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" ]'> 
+0

谢谢,这真是帮了!我在上面包含了我的更新代码,并进行了一些格式调整。 PHP回声不喜欢括号和括号。 – BlueHelmet