How Can I Make WordPress's <?php the_title_attribute(); ?> Render %20 for Spaces?
I'm trying to render a WordPress theme that is 100% HTML5 compliant, and have managed my way through all but one snag.
At the end of certain posts I show a "Tweet" link, which uses the following source code in the Theme template:
<a href="http://twitter.com/share?text=<?php the_title_attribute(); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>
HTML5 forbids having spaces in URLs. They must be rendered as %20
. However, <?php the_title_attribute; ?>
renders an XHTML safe version of the Post Title with spaces maintained.
An example URL (rendered using the template source code above):
a href="http://twitter.com/share?text=Twitter, Reblog, and Email Comments&via=ianhines&url=http://ihin.es/eCoYN9" title="Share This Article on Twitter">Tweet</a>
Is there any w开发者_StackOverflow社区ay I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?
Well, just wrap the the_title_attribute()
with urlencode()
:
/share?text=<?php echo urlencode(the_title_attribute()); ?>&via=
Edit: Ok, due to that comment, you'd need to do something like this:
<?php
ob_start();
the_title_attribute();
$title = ob_get_clean();
?>
/share?text=<?php echo urlencode($title); ?>&via=
Edit2: Looking at the docs for the_title_attribute
:
/share?text=<?php echo urlencode(the_title_attribute('echo=0')); ?>&via=
A value of 0 passed to the_title_attribute()
makes it return rather than echo it's result.
<?php
$urltitle= str_replace(' ','%20',the_title_attribute('echo=0')); //value of 0 to return rather than echo result
?>
<a href="http://twitter.com/share?text=<?php echo $urltitle; ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>
<?php
$spaceurl=the_title_attribute('echo=0');
$nonspaceurl=preg_replace('\s','%20',spaceurl);
?>
<a href="<?php echo $nonspaceurl; ?>">
my link text
</a>
EDIT
I added echo=0
to return the text instead of displaying it, see the_title_attribute
.
My suggestion would be to use the echo param of the_title_attribute()
and urlencode()
the spaces:
<a href="http://twitter.com/share?text=<?php echo urlencode(the_title_attribute('', '', 0)); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>
精彩评论