Вопрос

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