Skip to content

Instantly share code, notes, and snippets.

@jdembowski
Created October 12, 2015 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdembowski/9b438ce8ddf7c24d8aa9 to your computer and use it in GitHub Desktop.
Save jdembowski/9b438ce8ddf7c24d8aa9 to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: GModules Rewrite Links
Description: This will filter links in posts, pages, and comments to use "http://gmodules.com/ig/proxy?url=" instead.
Version: 1.0
*/
add_filter( 'the_content' , 'mh_gmodule' , 50 );
add_filter( 'the_content_rss' , 'mh_gmodule' , 50 );
add_filter( 'comment_text' , 'mh_gmodule' , 50 );
add_filter( 'comment_text_rss' , 'mh_gmodule' , 50 );
function mh_gmodule( $content ) {
// Regex to put all <a href="http://some-url-here/path/etc" into an array
$mh_url_regex = "/\<a\ href\=\"http\:\/\/[a-zA-Z0-9\-\.]+[a-zA-Z]{2,3}.*\"/";
preg_match_all( $mh_url_regex , $content, $mh_matches );
// Go through that array and add gmodules hack
for ( $mh_count = 0; $mh_count < count( $mh_matches[0] ); $mh_count++ )
{
$mh_old_url = $mh_matches[0][$mh_count];
$mh_new_url = str_replace( '<a href="http://' , '<a href="http://gmodules.com/ig/proxy?url=http://' , $mh_matches[0][$mh_count] );
// Array of destinations we don't want to apply the hack to.
// Some sites such as core.trac.wordpress.org don't work with the gmodules hack
// Partial matches work here, the more specific the better.
$mh_ignore = array(
home_url( '/' ),
'trac.wordpress.org/'
);
// Make the substitution on all links except the ignore list
if( !mh_array_find( $mh_old_url , $mh_ignore ) )
$content = str_replace( $mh_old_url , $mh_new_url , $content );
}
return $content;
}
// Only see if the array element is contained in the string
function mh_array_find( $needle , $haystack ) {
if(!is_array($haystack)) return false;
foreach ($haystack as $key=>$item) {
// See if the item is in the needle
if (strpos($needle, $item ) !== false) return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment