WordPress Code Snippets

A fresh mix of code snippets and tutorials

Display a Simple “Tweet This” Link


Twitter changes their API quite a bit, however it is still possible to display a simple “tweet this” link anywhere on your web pages.

Basic Tweet This Link

Here is the current format for displaying a “tweet this” link for Twitter:


To use this in a clickable link that we can include on any web page, we can write:

When clicked and tweeted, that link will result in a simple “Hello World” message.

Tweet This via WordPress

Of course, we want users to tweet something other than “Hello World”, so let’s use some WordPress template tags to include the post title and post permalink:

That results in a tweet that looks like this:

Currently reading The Post Title: https://example.com/post/url/

Encoding the URL

In order to use valid URLs with no unsafe characters, we need to encode the text that is output for the query string. We can do that with PHP’s urlencode(), like so:

Here is a close-up of the code used to generate the query string:

<?php echo urlencode('Currently reading '. get_the_title() .': '. get_permalink()); ?>

Note that for the template tags to work, the tweet-this link must be included in the WP Loop. Or alternately you can pass each of the tags the current post ID and do it that way instead. Of course, if you are not using WordPress, you will need to modify the output according to your own needs.

Use a Shortlink

As you know, tweets are limited in length to 140 characters, so let’s replace get_permalink() with wp_get_shortlink() to shorten up the URL that’s included in the tweet text. Returning to our previous example, we would change it to this:

<?php echo urlencode('Currently reading '. get_the_title() .': '. wp_get_shortlink()); ?>

That will produce a tweet that includes the short URL of the current Post or Page, like so:

Currently reading The Post Title: http://example.com/?p=1234

Depending on the actual permalink URL, using wp_get_shortlink() can really help cut down on the number of required characters. So you can hit that 140-character mark.

Bonus: Tweet This Shortcode

Let’s make it easy to display the Twitter link in any Post or Page using a Shortcode.

Once that’s included in your theme’s functions.php, you can display the tweet link by adding the shortcode:


Ta-da! You are ready to rock & roll my friend.

References & Resources

Learn more

WordPress Themes In Depth

Show Support

Like our new Facebook Page to show support!