I would let something like Google Analytics do the tracking for you with something like event tracking. Look into Yoast's Google Analytics plugin, it will let you do this fairly easily.
Otherwise, something like Redirection would be good for creating redirects. And, of course, you can see how many times each was clicked. I've used the plugin for years now and it's pretty good.
If you want to do something automatically, You'd need to create a custom rewrite rule and query variable:
<?php
add_action( 'init', 'wpse36168_add_rewrite_rule' );
/**
* Add our rewrite rule
*/
function wpse36168_add_rewrite_rule()
{
add_rewrite_rule(
'^go/(.*?)$',
'index.php?go=$matches[1]',
'top'
);
}
add_filter( 'query_vars', 'wpse36168_add_go_var' );
/**
* Tell WP not to strip out or "go" query var
*/
function wpse36168_add_go_var( $vars )
{
$vars[] = 'go';
return $vars;
}
Then hook into template_redirect
to throw people to the other URL if that query variable is caught.
<?php
add_action( 'template_redirect', 'wpse36168_catch_external' );
/**
* Catch external links from our "go" url and redirect them
*/
function wpse36168_catch_external()
{
if( $url = get_query_var( 'go' ) )
{
wp_redirect( esc_url( $url ), 302 );
exit();
}
}
And finally, you can hook into the_content
to auto replace all external links with the yoursite.com/go/someurlhere.com/asdf
links.
<?php
add_filter( 'the_content', 'wpse36168_replace_links', 1 );
/**
* Replace external links with our "go" links
*/
function wpse36168_replace_links( $content )
{
$content = preg_replace_callback( '%<a.*?href="(.*?)"[^<]+</a>%i', 'wpse36168_maybe_replace_links', $content );
return $content;
}
function wpse36168_maybe_replace_links( $matches )
{
if( ! preg_match( sprintf( '#^%s#i', home_url() ), $matches[1] ) )
{
$url = $matches[1];
// http:// we'll add it later
$url = str_replace( 'http://', '', $url );
$url = sprintf( '/go/%s', $url );
return str_replace( $matches[1], home_url( $url ), $matches[0] );
}
else
{
return $matches[0];
}
}
Here's all of that mess as a plugin.