A comma issue with foreach

2019-09-13 03:39发布

I have this code. This code is used to display all categories in WordPress.

foreach((get_the_category()) as $category) {
    echo $category->cat_name . ', ';
}

But even when there's just 1 category showing, the comma behind it is still there. I want it like this:

  • 1 category: [category]
  • 2 categories: [category], [category]
  • And same goes for 3 categories: [category], [category], [category]

Is this possible? I have tried:

foreach((get_the_category()) as $category) {
    $getcount = count(get_the_category());
    if($getcount > 1) {
        echo $category->cat_name . ', ';
    } else {
        echo $category->cat_name;
    }
}

But that's also not the best solution and when there's more than 1 category, the same issue will accur.

Help is much appreciated.

标签: php wordpress
5条回答
看我几分像从前
2楼-- · 2019-09-13 04:09

try using this.

   $str = '';
        foreach((get_the_category()) as $category) {
            $str .= "$category->cat_name , ";
        }
    $str = rtrim($str,', ');
  echo $str;
查看更多
戒情不戒烟
3楼-- · 2019-09-13 04:12

You could use implode:

$categories = []
foreach((get_the_category()) as $category) {
    $categories[] = $category->cat_name;
}

echo implode(', ', $categories);

Or you may use implode with array_map:

echo implode(', ', array_map(function($category) {
    return $category->cat_name;
}, get_the_category()));
查看更多
聊天终结者
4楼-- · 2019-09-13 04:13

You could use implode()

$categories = array()
foreach((get_the_category()) as $category) {
    $categories[] = $category->cat_name;
}
echo implode( ', ', $categories );
查看更多
时光不老,我们不散
5楼-- · 2019-09-13 04:15

why don't you use the_category(', ');? It will also list all post categories

查看更多
时光不老,我们不散
6楼-- · 2019-09-13 04:22

The easiest way is simply to use implodeafter building up an array of Category Names within your foreach Loop. And it takes just a few lines like so:

    <?php
        $catNames = array();
        foreach( (get_the_category()) as $category) {
            $catNames[] = $category->cat_name;
        }
        echo implode(', ', $catNames);
查看更多
登录 后发表回答