WordPress – make all images inside a post links

Recently, I have had this request from a friend of mine, who had trouble with adding images into their post.

In the following code, you will find “thickbox no_icon”, which is added for the plugin “auto-thickbox” used in that site. Enjoy!

/*  Make all images inside the post links */ 
function make_all_images_links($content) {
 	// Make a list of images with a link
 	$list_with_links = array();
 	preg_match_all('#<a ([^>]*)><img ([^>]*)></a>#is', $content, $matches);
 	foreach ($matches[2] as $key=>$value) 	{
 		if (strstr($value, '/wp-content/uploads/'))
 		{
 			preg_match('#src="([^"]*)"#is', $value, $match);
 			$list_with_links[$match[1]] = $match[1];
 		}
 	}
 	// Get all the other images
 	preg_match_all('#<img ([^>]*)>#is', $content, $matches);
 	foreach ($matches[0] as $key=>$value) 	{
 		if (strstr($value, '/wp-content/uploads/'))
 		{
 			preg_match('#src="([^"]*)"#is', $value, $match);
 			$image = $match[1];
 			if ( !isset($list_with_links[$image]) )
 			{
 				preg_match('#-([0-9]*)x([0-9]*)#', $image, $parts);
 				if (isset($parts[0])) { $image = str_replace($parts[0], "", $image); }
 			 	$content = str_replace($value, '<a class="thickbox no_icon" href="'. $image .'">'.$value.'</a>', $content);
 			}
 		}
 	}
 	return $content;
}
add_filter( 'the_content', 'make_all_images_links', 99999 );Code language: PHP (php)