Ian P. Hines Ian P. Hines - 1 year ago 105
PHP Question

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(); ?>&amp;via=ianhines&amp;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
. 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 way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

Answer Source

Well, just wrap the the_title_attribute() with urlencode():

/share?text=<?php echo urlencode(the_title_attribute()); ?>&amp;via=

Edit: Ok, due to that comment, you'd need to do something like this:

$title = ob_get_clean();
/share?text=<?php echo urlencode($title); ?>&amp;via=

Edit2: Looking at the docs for the_title_attribute:

/share?text=<?php echo urlencode(the_title_attribute('echo=0')); ?>&amp;via=
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download