[FIXED] PHP: Only show first word of a custom taxonomy

Issue

This is my code for displaying a taxonomy (WordPress):

 <?php
    $locations = get_the_terms($post->ID , 'location');
        foreach ($locations as $location) {
            echo '<div class="term-location">';
            echo $location->name . ' ';
            echo '</div>';
    }
?>

How can I modify the code to only display the first word of the taxonomy? I’ve tried it using explode but I can’t get it to work (since my php knowledge is limited).
Thanks in advance!

Solution

You can indeed use explode so you were on the right path!

Explode returns an array of strings. So you first use explode, and then select the first item.

$locations = get_the_terms($post->ID , 'location');
    foreach ($locations as $location) {
        echo '<div class="term-location">';
        echo explode(' ', $location->name)[0] . ' ';
        echo '</div>';
}

You can get more info on explode here, and an example on getting the first word here.

Answered By – thomasberends

Answer Checked By – Marilyn (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published