Reputation: 17561
There seems to be a bug in a Wordpress PHP function that leaves whitespace in front of the title of the page generated by <?php echo wp_title(''); ?>
I've been through the Wordpress docs and forums on that function without any luck.
I'm using it this way <body id="<?php echo wp_title(''); ?>">
in order to generate an HTML body tag with the id of the page title.
So what I need to do is strip that white space, so that the body tag looks like this <body id="mypage">
instead of this <body id=" mypage">
The extra white space kills the CSS I'm trying to use to highlight menu items of the active page. When I manually add a correct body tag without the white space, my CSS works.
So how would I strip the white space? Thanks, Mark
Part Two of the Epic
John, A hex dump was a good idea; it shows the white space as two "20" spaces. But all solutions that strip leading spaces and white space didn't.
And, <?php ob_start(); $title = wp_title(''); ob_end_clean(); echo $title; ?>
gives me < body id ="">
and <?php ob_start(); $title = wp_title(''); echo $title; ?>
gives me < body id =" mypage">
Puzzle. The root of the problem is that wp_title has optional page title leading characters - that look like chevrons - that are supposed to be dropped when the option is false, and they are, but white space gets dumped in.
Is there a nuclear option?
Yup, tried them both before; they still return two leading spaces... arrgg
Upvotes: 7
Views: 24897
Reputation: 1
add this to your functions.php
add_filter('wp_title', create_function('$a, $b','return str_replace(" $b ","",$a);'), 10, 2);
should work like a charm
Upvotes: 0
Reputation: 362117
Strip all whitespace from the left end of the title:
<?php echo ltrim(wp_title('')); ?>
Strip all whitespace from either end:
<?php echo trim(wp_title('')); ?>
Strip all spaces from the left end of the title:
<?php echo ltrim(wp_title(''), ' '); ?>
Remove the first space, even if it's not the first character:
<?php echo str_replace(' ', '', wp_title(''), 1); ?>
Strip only a single space (not newline, not tab) at the beginning:
<?php echo preg_replace('/^ /', '', wp_title('')); ?>
Strip the first character, whatever it is:
<?php echo substr(wp_title(''), 1); ?>
From the Wordpress documentation on wp_title
, it appears that wp_title
displays the title itself unless you pass false
for the second parameter, in which case it returns it. So try:
<?php echo trim(wp_title('', false)); ?>
Upvotes: 38
Reputation: 11
Thanks for this info! I was in the same boat in that I needed to generate page ids for CSS purposes based on the page title and the above solution worked beautifully.
I ended up having an additional hurdle in that some pages have titles with embedded spaces, so I ended up coding this:
<?php echo str_replace(' ','-',trim(wp_title('',false))); ?>
Upvotes: 1
Reputation: 16871
Just to throw in some variety here: trim
<body id="<?=trim(wp_title('', false));?>">
Upvotes: 1