How Can I Make WordPress’s <?php the_title_attribute(); ?> Render 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:

Read More
<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 %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 way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

Related posts

Leave a Reply

4 comments

  1. 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:

    <?php
    ob_start();
    the_title_attribute();
    $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=
    
  2. 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; ?>&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>
    
  3. 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)); ?>&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>