Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@davidnunez
Last active December 9, 2021 04:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidnunez/c1e3f1fa06cf5545d100 to your computer and use it in GitHub Desktop.
Save davidnunez/c1e3f1fa06cf5545d100 to your computer and use it in GitHub Desktop.
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);
@davidnunez
Copy link
Author

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

@davidnunez
Copy link
Author

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