January 20th, 2013, 03:04 AM
Substr not working with variables
I've been trying to use the substr() function but I'm having a problem with variables and it's driving me crazy.
Here is the code. wp_title() is a WordPress tag.
<?php $pgtitle = wp_title(); echo $pgtitle; ?>
So far so good, everything works. The code outputs the title of the page.
<?php $pgtitle2 = substr($pgtitle, 0, 4); echo $pgtitle2; ?>
This does NOT work. Nothing is outputed. I don't get it. If I use something like 'abcde' instead of $pgtitle the code works. Help!
January 20th, 2013, 04:59 AM
And I take it you had a $pgtitle=wp_title(); before that line? Or
$pgtitle = substr(wp_title(), 0, 4); echo $pgtitle;
January 20th, 2013, 07:47 AM
Yes, the whole code is
Originally Posted by requinix
That actually does print the page title, but it prints the entire title, and not just what I'm trying to extract with the substr() function. Moreover, if I write this (like my original example):
$pgtitle = wp_title(); $pgtitle2 = substr($pgtitle, 0, 4); echo $pgtitle2;
I only get one of them printed. I'm not sure if it's the $pgtitle or the $pgtitle2 that is being printed but it's very strange that only one of them gets printed.
$pgtitle = wp_title(); echo $pgtitle; $pgtitle2 = substr($pgtitle, 0, 4); echo $pgtitle2;
Last edited by FRUGiHOYi; January 20th, 2013 at 07:57 AM.
January 20th, 2013, 10:35 AM
A lot of WordPress functions echo their return value by default rather than returning it. (Yet another consequence of WordPress having been built by front-end people without input from back-end architects)
Take a look at the documentation page for wp_title, because I believe that is the case here. However, also note that the documentation seems to be wrong regarding the second parameter.
January 20th, 2013, 02:25 PM
Figured it out. I have to use the WordPress function the_title() instead of wp_title. If I pass the last parameter as FALSE, then the title of the page is returned for use in PHP and I can use the substr() function on it. So the entire code is
Only the first four characters of the page title are echoed
$pgtitle = substr(the_title('','',FALSE), 0, 4); echo $pgtitle;