Home > database >  PHP: Only show first word of a custom taxonomy
PHP: Only show first word of a custom taxonomy

Time:08-30

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

 <?php
    $locations = get_the_terms($post->ID , 'location');
        foreach ($locations as $location) {
            echo '<div >';
            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!

CodePudding user response:

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 >';
        echo explode(' ', $location->name)[0] . ' ';
        echo '</div>';
}

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

  • Related