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];
?>
this is very easy:
or
untested, but should work 🙂
Hope this is helpful 🙂
or in your template file
explode by space and get first element in resulting array
You can do like this:
I think you’re probably running into some of the idiosyncrasies of WordPress here. the_title(), by default, just prints out the title and returns nothing. In order to make it return the title string instead of printing it, you have to set the third parameter of
the_title()
to true.Once you have it, then you can get rid of the first word and echo it manually. If you’re using PHP 5.3, you can accomplish this in one line with strstr():
If you have PHP < 5.3, you can use
explode()
:I would recommend avoiding this string parsing entirely and using a more general approach for defining a secondary title for your page.
You should use WordPress’ Post Meta system to define a custom meta field with a name like ‘subtitle’, then call that field in your template. That way you can decide on a page-by-page basis what you want the subtitle to be, rather than being locked into a specific relationship between post title and subtitle. This probably won’t make your life more complicated and it will simplify it significantly.
You add post meta to a page or post using the “Custom Fields” section at the bottom of the post editing screen. You display those fields in your theme like this:
Obviously you’d probably be better off checking it exists first, giving you something like this:
More details on the codex.
There is a string function (strtok) which can be used to split a string into smaller strings (tokens) based on some separator(s). For the purposes of this thread, the first word (defined as anything before the first space character) of
Test me more
can be obtained by tokenizing the string on the space character.For more details and examples, see the strtok PHP manual page.