Ampersands in WordPress titles break my share to social media links

I was hoping to get some help with a bit of a coding problem that has been driving me crazy. I’d preferably like to write “&” instead of “and” in my wordpress post titles. But writing out ampersands breaks our post share links for twitter, facebook, and google-plus. Facebook is able to actually display the link (it takes the ampersand out of the title, though), but twitter full out fails, and google-plus as well.

This is the code for the share links:

Read More
<ul>
    <li class="video-twitter"><a target="_blank" href="http://twitter.com/share?text=<?php the_title(); ?>&amp;url=<?php the_permalink(); ?>" title="Share on Twitter">Twitter</a></li>
    <li class="video-facebook"><a target="_blank" href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>" title="Share on Facebook">Facebook</a></li>
    <li class="video-google"><a target="_blank" href="https://plus.google.com/share?url=<?php the_permalink();?>&t=<?php the_title(); ?>" title="Share on Google+">Google+</a></li>
</ul>

Any help would be greatly appreciated!

Related posts

Leave a Reply

1 comment

  1. I had the same problem today and it’s rather easy to fix. All ampersands and such are served as entities by WordPress, this means if you use get_the_title() or the_title() ampersands are like this: & #038 ;

    You can decode this using html_entity_decode() after that you’ll have to make it URL friendly, which can be done using urlencode().

    Combine them and you’ll have this:

    <?php print urlencode( html_entity_decode( get_the_title() ) ); ?>
    

    Or do it the ‘cleaner’ way and create this function in your functions.php theme file:

    function themeprefix_social_title( $title ) {
        $title = html_entity_decode( $title );
        $title = urlencode( $title );
        return $title;
    }
    

    This way you can call this function in your theme, which can be used for all social networks:

    <?php print themeprefix_social_title( get_the_title() ); ?>
    

    When applied to your example:

    <ul>
        <li class="video-twitter"><a target="_blank" href="http://twitter.com/share?text=<?php print themeprefix_social_title( get_the_title() ); ?>&url=<?php the_permalink(); ?>" title="Share on Twitter">Twitter</a></li>
        <li class="video-facebook"><a target="_blank" href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php print themeprefix_social_title( get_the_title() ); ?>" title="Share on Facebook">Facebook</a></li>
        <li class="video-google"><a target="_blank" href="https://plus.google.com/share?url=<?php the_permalink();?>&t=<?php print themeprefix_social_title( get_the_title() ); ?>" title="Share on Google+">Google+</a></li>
    </ul>