Yagayente Yagayente - 3 months ago 15
PHP Question

Make category words appear separately on ACF

I am using ACF taxinomy sub field. I am searching for a way to display multiple categorys from this field. The code I am using display all categories but the word touch each other, and don't separate.
How to make those category words appear separately ?

<?php
$term = get_sub_field('categories');
if( $term ) {
foreach($term as $t) {
$t = get_category($t);
echo $t->name;
}
}
?>


see the category in gray on this picture

Answer

You just need to concatenate a space to your category names. You can achieve this in multiple ways.

The simplest way would be:

<?php
$term = get_sub_field('categories');
if ($term) {
    foreach ($term as $t) {
        $t = get_category($t);
        echo $t->name . ' ';
    }
}

This way concatenates a space ' ' after each element. So your string will end up with a final space (also called trailing whitespace). This may be an issue or maybe not.

Another way:

<?php
$term = get_sub_field('categories');
if ($term) {
    $first = true;
    foreach ($term as $t) {
        $t = get_category($t);
        echo ($first ? '' : ' ') . $t->name;
        $first = false;
    }
}

This time we use a boolean $first variable and the ternary operator Shorthand If/Else to concatenate the space before each element except the first one. This way your HTML code gets a clean string (without trailing spaces).

Even another way to get a clean string would be:

<?php
$term = get_sub_field('categories');
if ($term) {
    $cats = [];
    foreach ($term as $t) {
        $t = get_category($t);
        $cats[] = $t->name;
    }
    echo implode(' ', $cats);
}

In this example we push all category names to $cats array to finally convert (and echo) this array to string with implode.

I hope this helps you to understand it! :)

Comments