Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Automatically Unshortening Links in Wordpress Posts
function unshorten_url($url) {
$ch = curl_init($url[0]);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => TRUE, // the magic sauce
CURLOPT_RETURNTRANSFER => TRUE
CURLOPT_HEADER => TRUE,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_SSL_VERIFYHOST => FALSE, // suppress certain SSL errors
CURLOPT_SSL_VERIFYPEER => FALSE,
));
curl_exec($ch);
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
$url = preg_replace( '/&?utm_.+?(&|$|\s)/', '', $url );
$url = str_replace("%5C", '', $url); // hack - sometimes wikipedia appends a backslash
$url = rtrim($url, "?");
return $url;
}
function find_links_for_unshortening($text) {
$pattern = "#\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.])(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'\".,<>?«»“”‘’\s]))#i";
$text = preg_replace_callback($pattern,'unshorten_url',$text);
return $text;
}
add_filter('content_save_pre', 'find_links_for_unshortening', 999);
Owner

davidnunez commented Aug 21, 2015

Updated 2015-08-20-1042 - fixed links & changed code for better regex and to contain url fixing to urls only (and not full text of post)
Updated 2015-08-21-1229 - added wikipedia hack

Owner

davidnunez commented Aug 21, 2015

Just add this code to the functions.php of your WordPress theme and you’re on your way to abandoning shortened links whenever you save or update a post.

see http://www.davidnunez.com/2015/08/19/automatically-unshortening-links-in-wordpress-posts/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment