-
-
Save deckerweb/5908349 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Mask Outbound Links | |
Plugin URI: http://www.christopherguitar.net/ | |
Description: Masks outbound links behind a redirect | |
Author: Christopher Davis | |
Author URI: http://www.christopherguitar.net/ | |
License: GPL2 | |
*/ | |
register_activation_hook( __FILE__, 'wpse36168_activation' ); | |
/** | |
* Activation hook. flushes rewrite rules and adds ours. | |
*/ | |
function wpse36168_activation() | |
{ | |
flush_rewrite_rules(); | |
wpse36168_add_rewrite_rule(); | |
} | |
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; | |
} | |
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(); | |
} | |
} | |
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]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment