How to Link all images to the Post Permalinks automatically in WP

With Ready to use Codes for WordPress

Recently, while working a WordPress project I came to the situation where I needed to link all the post images to their respective post permalinks.

But why would anyone want to do this ?

In my case, as the site was basically image based so it needs to show the images even on the homepage and  in the excerpts too, so the problem was that the people would more likely to click the image instead of ‘read more‘ link or the title of the post, but when they click they get redirected to the attachment page or to the image and I think nobody would like that.


So, What is the solution ?

After a few hours of thinking I came with a solution that can automatically replace the image hyperlinks (links within the <a href””>) with the post permalinks, actually i think it’s not a perfectly great solution but it does what i wanted.

Basically the idea involved several steps, which are:

1. While loading the site for the user, take each post’s content

2. Search for images in the content

3. Use ‘preg_replace ‘ function of PHP to change the links

4. Finally, return the modified content to the user

Limitations of this solution are that the modified content is not saved in the database of the site, actually its not a limitation I just didn’t got any reason to save the modified content to the DB so I made it straight and simple, but if you want that too, I might help.

Ready to Use Code

I have finally compiled a code that would work out of the box for any WordPress install and theme, if you want this then just copy and paste this code into your theme’s function.php via the theme editor or FTP access.

add_filter( 'the_content', 'image_link_permalink' );

function image_link_permalink( $content ) {
	$post_link = get_permalink();
	$content =
        preg_replace(array('{<a[^>]*><img}','{/></a>}'), array('<a href="'.$post_link.'"><img','/></a>'), $content);
	return $content;

If you are using any caching plugin, don’t forget to clear the cache after saving the changes to the function.php and if you still face any issue, let me know via comments.

0 Responses on How to Link all images to the Post Permalinks automatically in WP|

Leave a Message

Your email address will not be published. Required fields are marked *

CommentLuv badge

Pin It on Pinterest