How to encode WordPress content properly for sharing at Twitter? (Twitter web intents & share)

Wordpress encoding content for Twitter intent
If you want to create your own Twitter share button at your WordPress blog probably you’d hit an issue related with how content & URL variables are handled which causes some special characters like “&” to break the Twitter web intent/share URL . You have to encode the piece of content that you pass as a variable.

Twitter asks for proper encoding of your variables. You can read more about at Twitter web intents docs.

For the developers this issue is probably easy to solve with some common php functions like urlencode()

Meanwhile, if you’re a WordPress user and if some of titles of your posts involve special characters, you experience a glitch and at Twitter sharing window instead of a correctly typed symbols, you receive encoded characters. Most common case is receiving “%26”s instead of “&”s .

If you’re a wordpress user but not an avid developer, below is my solution that is based on javascript:

Share this information at Twitter

<a onclick="var msg='<?php the_title(); ?>';var url='<?php the_permalink(); ?>';var link='https://twitter.com/intent/tweet?url=' + encodeURIComponent(url) + '&text='+ encodeURIComponent(msg) + '&related=ogomogo&via=ogomogo'; window.open(link);" href="#" title="Twitter">Share on Twitter</a>

You have to insert this into your single.php file or index.php file or wherever you want the Twitter share button to appear inside the Loop.

Leave a Reply

Your email address will not be published. Required fields are marked *