Wordpress - How to display only 3 main categories, separated by commas, since they are marked in the post?

It should be enough using a single <span> for all categories and add some logic.:

<span><?php
$categories = ['horses','dogs','birds'];
$string = "";

foreach ($categories as $category){ //iterate over the categories to check
    if(has_category($category))
        $string .= $category.", "; //if in_category add to the output
}

$string = trim($string); //remove extra space from end
$string = rtrim($string, ','); //remove extra comma from end
echo $string; //result example: <span>horses, dogs</span>
?></span>

Tags:

Categories