Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP: Only show first word of a custom taxonomy

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading