Post WordPress To Twitter Automatically, With Short URLs, No Plugin Required

Updated: Found a Fix for the missing post id at the end of the url using $postLink = urlencode ( $postLink ) ;

Updated: Got rid of the Custom Metadata, used the modified date and the created date of the post to check if its a new post or an old one. Now you don’t have to worry about updating your old posts.

Updated: To Make the title text more Twitter friendly.

I been trying to cut down on the number of Plugins used. Firstly to make maintained easier, secondly to simplify and reduce to the bare minimum without using Plugins, thirdly to hone up my WordPress skills. The latest plugin I got rid of was the WP to Twitter Plugin. Initially I started off trying to modify how I wanted it to work. Basically I wanted to cut off as a URL shortner and use my own blog as a URL shortner to send people directly to my site and keep the traffic on my site without the need for a middle man. I figured this out after I saw how Amit Aggarwal was tweeting his links to his site.

Short URLs in WordPress without or URL Shortners

We all know that WordPress generates long Permalinks for your site, it automatically converts your titles into those long URLs called permalinks that you see. Example, If you switch off Permalinks in WordPress you’ll see that links to your posts will be of the form if you look at it you’ll notice the last bit has a number attached to it, each post has a unique ID associated to it. The trick is to make use of this ID to and create a URL for our posts, so when people click on this shortned link they’ll be automatically taken to the Permalink associated with that post its as simple as that.

A Simple WordPress To Twitter Function.

First we’ll write a really simple function that uses CURL to post to the Twitter API. Just copy paste it into your functions.php file in your WordPress theme directory. In case you don’t see the file in yours themes folder just create one and paste the code inside it. To check if CURL is enabled on your server you can paste this function into a blank PHP file and call the function like this twitterUpdate("some random post", "", true); with some random inputs. Make sure you uncomment the last few lines where it says to uncomment to test for CURL support.

Note: In the rare case your host does not support CURL you can always make use of fsockopen for PHP 4 or the much easier stream_context_creat for PHP5

function twitterUpdate($postTitle, $postLink, $isNew)
	// Enter Your Twitter ID Here
	$username = 'Twitter_ID';
	// Enter Your Twitter Password Here
	$password = 'Password';

        # text into a twitter friendly text
	$code_entities_match = array('--','"','!','@','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','.','/','*','+','~','`','=');
	$code_entities_replace = array('-','','','','','','','','','','','','','','','','','','','','','','','','');
	$postTitle = str_replace($code_entities_match, $code_entities_replace, $postTitle);

	// Check if New or Updated Post
		$postTitle = 'New Post: ' . $postTitle;
		$postTitle = 'Updated Post: ' . $postTitle;

	// Calculate Twitter Msg and keep it under 140 Chars
        if(strlen ($postTitle) > (140 - strlen ($postLink)))
		$postTitle 		= substr_replace($postTitle, '...', (140 - 3 - strlen ($postLink)));

	$message = $postTitle . $postLink;

	// The twitter API address
	$url = '';
	$curl_handle = curl_init();
	curl_setopt($curl_handle, CURLOPT_URL, "$url");
	curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
	curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl_handle, CURLOPT_POST, 1);
	curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
	curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
	$buffer = curl_exec($curl_handle);

	// Uncomment the lines below to check if
	// CURL is enabled on your Web Server
	// check for success or failure
	if (empty($buffer))
		echo 'message';
		echo 'success';

WordPress Function that Triggers Post To Twitter

Next we’ll write a simple wordpress function that triggers whenever you update or publish a post, we will also added a custom metadata to the post check if its a new or old post. Copy paste this code below the twitterUpdate function in your functions.php themes file.

function postToTwitter($post_ID)
	// Create your Short URL replace with your blog url
	$postLink = '' . $post_ID;
	// encode the URL to fix Post to Twitter issues
        $postLink = urlencode  ( $postLink ) ;
	// Get the Post Object
	$get_post_info 	= get_post( $post_ID );
	// Get the Post Title
	$postTitle = $get_post_info->post_title;
        // Get the Post date
	$postDate 		= date('U', strtotime($get_post_info->post_date));
	// Get the post Modified date
	$postModified 	= date('U', strtotime($get_post_info->post_modified));

	// Check if the post is new or modified
	if($postModified == $postDate)
		twitterUpdate($postTitle, $postLink, true);
	/*  If You want to fire everytime You update
	      a post remove these comments around the else.
		twitterUpdate($postTitle, $postLink, false);

// Post to twitter when you publish or update a post
add_action('publish_post', 'postToTwitter');

So thats about it, just paste these two blocks of code into your functions.php and change the required parameter, you can play around with the code and modify it to change the message being posted to twitter.

22 Responses

Thanks for this post. I tried the code, but found that twitter did not include the /?p=876 in the link. It would only show the domain name. Do you have any thoughts why this would be?

Hey Jason the code given above works perfectly for me. Are you sure you copy pasted the code I gave you correctly?

Hey Jason I have updated the code, I think I found a solution to the problem you were having, it to do with the URL encoding, check the post to see the change its only one line.

after the following code line

$postLink = '' . $post_ID;

add this

$postLink = urlencode ( $postLink ) ; –> ?p=364 <– that post ID part is not showing up on twitter as part of the link. same issue as Jason described. Copied and pasted the code as-is. Only updated the username, password, and blog url. Any suggestions Arpit????

ok I double checked and it seems to be working fine on my site

try changing

$message = $postTitle . $postLink; to

$message = $postLink . $postTitle;

i.e move the link in front of the title it might be getting truncated.

FIXED… Thanks for your update…. the $postLink = urlencode ( $postLink ) ; fixed my problem.

Thanks to Arpit for helping me find the solution to the fore-mentioned issue. It works beautifully now. Thanks mate!

hey guys you are welcome :) glad it got fixed. and luckily I didn’t have to spend too much time figuring it out.

Can i add this to my blog?

Hey tim you can’t use it on since they don’t allow you to edit or add any PHP code. You need to be on your own server i.e. self installed wordpress.

This is a very useful piece of code and I tried it successfully. But I was wondering whether or not it is possible to add URL instead of the default WP URL. I know the whole idea of this code is to post without any other plugin. But I really don’t like to post my WP URL as my domain name is a bit long. I know how to shorten WP urls automatically with but don’t know how to send that to Twitter. So, is it possible to call a link in $postLink?

Thank you very much boss, works like a charm

Thanks for this. Pretty cool. My one problem is, if I create a draft post this script does not see it as new when it finally gets published. It will work if I remove the comments around the ELSE section so that the script fires on updates but I don’t want that for other reasons.
Any thoughts on how to get this to work? I was thinking of somehow checking the status with $post->post_status but my php skills aren’t very good.
On twitter as @techlifeweb

This is brilliant, thank you so much. Do you know how i can stop the function running when a post is in a certain category?

I have a few categories i dont want tweeted.


great article, thanks for sharing.

Thank you very much for this code.

I have one question though. If I want to limit the number the automatic tweets, so Twitter only gets an update when I post on WordPress in a certain category. How can I add an filter to the code for that?

Hi all its 13th september 2010, is this code still valid/works?

Great hack..
If my url structure is like “category/post.html”.
Does it work with this url structure.

Tweets were not being posted. I uncommented to check for success or failure and received an error:

Warning: Cannot modify header information – headers already sent by (output started at functions.php:72) in /wp-includes/pluggable.php on line 890

Do you think this is theme specific? Has this been tested in the latest version of WP?

is working!!! try this
“ok I double checked and it seems to be working fine on my site

try changing

$message = $postTitle . $postLink; to

$message = $postLink . $postTitle;

i.e move the link in front of the title it might be getting truncated.”
as arpit jacob said. thanks AJ

I have been trying to get this to work for 2 days now and cant work out whats going wrong with it :(

It just dont post to my twitter account, I copied the code exact as in the original post and have double checked I put my twitter user and pass correctly and still not working :(

Can anyone tell me if something needs changing from the original code for it to work now or something?

Ok I just tried the changes you posted in the comments here and still it didnt work :(

MY blog is at if you could have a look to see if you can work it out as I see no reason for this not to work correctly.