ZetaLight
Learn, Share, Inspire, Ideas.

I been looking at ways to cut down on the number of plugins I use with WordPress. While WordPress does have a inbuilt mechanism to update plugins, I find it a hassle to keep them updated and sometimes I really don’t require most of the other functionality a wordPress plugin provides.

WordPress Short URLs In Twitter

Here is a small trick that is very useful in helping you maintain the link juice to your site and also to helps in avoid sending people to a third party URL shortner. Its very common to use a link shortner to reduce the number of characters a link takes up when you tweet.

If you care about SEO you will most probably be using WordPress Permalinks in the form of http://somesite.com/some_random_post/. You will notice, if Permalinks are not enabled, then by default your site links are in the form of http://somesite.com/?p=44 . The trick is to get the post id of whatever link you want to post on twitter and post it in the form of http://somesite.com/?p=44 this link will automatically redirect to your actual blog post as this is an inbuilt feature in wordpress called canonical URLs, not only does this reduces the character count but it also helps your twitter followers to go to your site directly without using any third party URL shortners.

Automatically Post Latest WordPress Articles To Twitter

We will use the tip I explained above to write a wordpress theme function that automatically posts a tweet to your twitter account whenever you write a new post or update any of your posts or articles. Before we use this function we’ll check if CURL is enabled on your server. All you need to do is to paste the function ¬†given below into a blank PHP file and call the function with some random inputs, somewhere on the same page like this twitterUpdate("some random post", "http://zetalight.com", true); . Make sure you uncomment the last few lines where it says to uncomment to test for CURL support. In the rare case your web host does not support CURL you will have to make use of fsockopen for PHP 4 or the much easier stream_context_creat for PHP5. Next make sure you have file called functions.php in your theme directory. I put comments before every line explain what is happening in the function. There are basically two functions one is the twitterUpdate function which take care of posting to twitter, the other one is postToTwitter function which is a function that calls the twitterUpdate only when a new post is created or updated. copy paste both these functions in your functions.php file and enter your twitter UserName and PassWord in the appropriate places.

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
	if($isNew)
		$postTitle = 'New Post: ' . $postTitle;
	else
		$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 = 'http://twitter.com/statuses/update.xml';
	$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);
	curl_close($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';
	else
		echo 'success';
	*/
}

function postToTwitter($post_ID)
{
	// Create your Short URL replace with your blog url
	$postLink = ' http://zetalight/?p=' . $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.
	else
	{
		twitterUpdate($postTitle, $postLink, false);
	}
	*/
}

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

Twitter To WordPress Widget

Here is another simple JavaScript code to display your latest twitter tweets in your sidebar, you can either use it as a widget or just paste it in your sidebar. Since its JavaScript based it doesn’t cause any load on your WordPress site and loads you latest tweets very fast. Not only does it get your latest tweets, but converts the links into hyperlinks and twitter profiles. You can copy paste this code into a text/html widget to get it working. make sure there is a DIV with ID="twitter" somewhere on the page, you can load the JavaScript separately in your footer if you want.

//Get the Twitter JSON Feed for the User
function getTweets(UserName, tweetCount)
{
	var twitterJSON = document.createElement("script");
	twitterJSON.type="text/javascript";
	twitterJSON.src=  "http://twitter.com/statuses/user_timeline/"+UserName+".json?callback=twitter_callback&count="+tweetCount;
	document.getElementsByTagName("body")[0].appendChild(twitterJSON);
};

//Twitter Call back function Replace 'twitter' with any Div ID name
function twitter_callback(twit)
{
	var twitterdiv = document.getElementById('twitter');
	var icon,who,what,when;
	for (i=0; i < twit.length; i++)
	{
		icon=twit[i].user.profile_image_url;
		who="@"+twit[i].user.screen_name;
		what=twit[i].text.linkify().atify();
		when=normalizeDate(twit[i].created_at);
		twitterdiv.innerHTML += what+' ('+who.atify()+' wrote '+when+')';
	}
};

// Function to convert links to hyperlinks
String.prototype.linkify = function()
{
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m)
	{
		return m.link(m);
	});
};

//function to conver twitter usernames into hyperlinks
String.prototype.atify = function() {
	return this.replace(/@[\w]+/g, function(m)
	{
		return '<'+'a href="http://www.twitter.com/'+m.replace('@','')+'">'+m+'';
	});
};

Convert date into human readable format.

//Get Humanreadable Date/time
function normalizeDate(time)
{
	var time_formats = [
		[60, 'Just Now'],
		[90, '1 Minute'], // 60*1.5
		[3600, 'Minutes', 60], // 60*60, 60
		[5400, '1 Hour'], // 60*60*1.5
		[86400, 'Hours', 3600], // 60*60*24, 60*60
		[129600, '1 Day'], // 60*60*24*1.5
		[604800, 'Days', 86400], // 60*60*24*7, 60*60*24
		[907200, '1 Week'], // 60*60*24*7*1.5
		[2628000, 'Weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
		[3942000, '1 Month'], // 60*60*24*(365/12)*1.5
		[31536000, 'Months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
		[47304000, '1 Year'], // 60*60*24*365*1.5
		[3153600000, 'Years', 31536000], // 60*60*24*365*100, 60*60*24*365
	];

	var values = time.split(" ");
		time = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time),
		dt = new Date,
		seconds = ((dt - new Date(parsed_date) + (dt.getTimezoneOffset() * 60000)) / 1000),
		token = ' Ago',
		i = 0,
		format;

	if (seconds < 0)
	{
		seconds = Math.abs(seconds);
		token = '';
	}

	while (format = time_formats[i++])
	{
		if (seconds < format[0])  		{ 			if (format.length == 2)  			{ 				return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
			}
			else
			{
				return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
			}
		}
	}
};

Resources and links that helped me JSON Feeds Callbacks with Twitter

Comments are closed.