Last active
December 9, 2021 04:31
-
-
Save davidnunez/c1e3f1fa06cf5545d100 to your computer and use it in GitHub Desktop.
Automatically Unshortening Links in Wordpress Posts
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
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); |
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
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