0
我有顯示爲網格的帖子列表,並且我需要每個帖子列出其自己的類別,用逗號分隔。我有一個功能代碼,但它只列出了一個類別。在循環內部列出帖子的類別列表
當前代碼:
<?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();?>
謝謝,這真是幫了!我在上面包含了我的更新代碼,並進行了一些格式調整。 PHP回聲不喜歡括號和括號。 – BlueHelmet