質問

im using

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

now this obviously outputs a comma at the end of each "category" how would i go about emoving the comma from the last item in the list?

役に立ちましたか?

解決

Use rtrim:

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

他のヒント

Here is another way to do it, using the join function-

echo join(",",array_map(function($category){return $category->cat_name;}, get_the_category()));

You can try this:

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

echo implode($categories, ',');
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top