Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

·
Free Resource
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.



  Twitter Tools plugin from Alex King 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≈iKey=R_0da49e0a9118ff35f52f629d2d71bf07
	$url = 'http://api.bit.ly/shorten?version=2.0.1&longUrl='.urlencode($long_url.$analytics).'&login='.$login.'≈iKey='.$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');
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}