【问题标题】:List array of post's categories inside loop在循环内列出帖子类别的数组
【发布时间】:2017-10-04 23:29:48
【问题描述】:

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

当前代码:

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

哪个输出&lt;figure data-groups='["category1"]&gt;

我需要的是&lt;figure data-groups='["category1","category2","category3"]&gt;

我确实看到了一个类似的问题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();?> 

【问题讨论】:

    标签: arrays wordpress loops foreach categories


    【解决方案1】:

    正如您在复制的代码中所见,$category_names 是一个数组。你不能像你做的那样echo一个数组来得到这个输出:

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

    试试:

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

    【讨论】:

    • 谢谢,这真的很有帮助!我在上面包含了我更新的代码,并进行了一些格式调整。 php echo 不喜欢方括号和圆括号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多