Get first word in string php the_title WordPress
15,660
Solution 1
this is very easy:
<?php
$title = get_the_title(); // This must be!, because this is the return - the_title would be echo
$title_array = explode(' ', $title);
$first_word = $title_array[0];
echo $first_word;
?>
or
<?php
$title = current(explode(' ', get_the_title()));
echo $title;
?>
untested, but should work :)
Hope this is helpful :)
Solution 2
$first_word = current(explode(' ', $title ));
or in your template file
<?php echo current(explode(' ', $title )) ?>
explode by space and get first element in resulting array
Solution 3
list($first_word) = explode(' ',$mystring);
Author by
HandiworkNYC.com
I make custom WordPress themes http://handiworknyc.com
Updated on June 05, 2022Comments
-
HandiworkNYC.com almost 2 years
I'm trying to shorten a wordpress title to just the first word. For a page named "John Doe" I want to have a sub title somewhere on the page that says "About John" so I want to just get the first word from the title.
Is there a way to do this with PHP?
Thanks!
UPDATE:
Thanks for your answers! I tried the following code but it doesn't seem to be working. It still echoes the full title. Any suggestions?<?php $title = the_title(); $names = explode(' ', $title); echo $names[0]; ?>