Wordpress: How to add commas in this get_the_categ

2019-09-01 05:15发布

PHP

<?php
     $categories = get_the_category();
     foreach ($categories as $category){
     echo $category->cat_name;}
?>

Currently this will display categories as "cat1cat2cat3" What I want it to be is "cat1, cat2, cat3"

I tried this echo $category->cat_name . ', '; but this just adds a comma after every category. Even if the post just has one category: Ex. "cat1, " And it also adds commas to the last category in the list: Ex. "cat1, cat2, cat3, "

So how can I get the commmas in but absent if just one category and absent on the last category if its a list?

标签: php wordpress
3条回答
Deceive 欺骗
2楼-- · 2019-09-01 05:30

you can do something like:

<?php

     $categories = get_the_category();
     $cat = '';
     foreach ($categories as $category){
         $cat .= $category->cat_name . ', ';
     }
     $cat = substr($cat,0,-2);
     echo $cat;
?>

best regards,

查看更多
The star\"
3楼-- · 2019-09-01 05:34

Try this: (As of PHP 5.3)

$categories = array_map(function($category) {
    return $category->cat_name;
}, get_the_category());

echo implode(', ', $categories);
查看更多
放荡不羁爱自由
4楼-- · 2019-09-01 05:35

You can also use implode() for that:

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