Wordpress: How to add commas in this get_the_categ

2019-09-01 04:42发布

问题:

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?

回答1:

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


回答2:

Try this: (As of PHP 5.3)

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

echo implode(', ', $categories);


回答3:

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,



标签: php wordpress