DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Add Bit.ly (or Other URL Shortener) And Google Analytics To Wordpress Twitter Tools Plugin

04.03.2009
| 8067 views |
  • submit to reddit
        I couldn't find this code anywhere, and it was simple enough to create, so here it is. A way to use bit.ly, or some other URL shortening service, with the Twitter Tools plugin for Wordpress. Just for fun I added in Google Analytics tracking, so you can get some additional stats. I recommend bit.ly though, since they already have stats built into their URL shortening platform.

<?php
/*
Plugin Name: bit.ly add-on for Twitter Tools
Plugin URI: http://www.mybanktracker.com
Description: Install <a href="http://alexking.org/projects/wordpress">Twitter Tools plugin from Alex King</a> for this plugin to work.
Version: 0.1
Author: Jason Reposa
Author URI: http://www.mybanktracker.com
*/

// Copyright (c) 2009 My Bank Tracker. All rights reserved.
//
// Released under the GPL license
// http://www.opensource.org/licenses/gpl-license.php
//
// **********************************************************************
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
// **********************************************************************

function tweet_track($long_url) {
	$analytics = '?utm_campaign=blog&utm_source=twitter&utm_medium=tweet';
	$login = 'YOUR_LOGIN';
	$api_key = 'YOUR_API_KEY';

	// From: http://code.google.com/p/bitly-api/wiki/ApiDocumentation
	// http://api.bit.ly/shorten?version=2.0.1&longUrl=http://cnn.com&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07
	$url = 'http://api.bit.ly/shorten?version=2.0.1&longUrl='.urlencode($long_url.$analytics).'&login='.$login.'&apiKey='.$api_key;

	$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$data = curl_exec($ch);
	curl_close($ch);

	if (!empty($data)) {
		$result = json_decode($data);
		if (!isset($results->errorCode) && $results->errorCode == 0) {
			return $result->results->{$long_url.$analytics}->shortUrl;
		}
	}

	// if all else fails return original
	return $long_url;
}

add_filter('tweet_blog_post_url', 'tweet_track');
// for testing on command line:
// echo tweet_track('http://www.mybanktracker.com');