How to add source links to image captions in WordPress

I needed to add some illustrative pictures to a blog article and I wanted to give proper credit to the photographers and link to their websites. I didn’t found a proper plugin that I liked so I created this solution.

If you are adding an image (or other media file) to the WordPress Media library you can set certain meta-data, like Caption, Alt-Text and Description. I wanted to make part of the Caption a clickable link that refers to the source/website of the picture to give proper credits to the original author. Unfortunately this is not really a common habit in the blog-o-sphere I’ve noticed (trying to find the sources of one original image), so it made even more sense to me to create a solution for proper attribution.

The most easy might be to switch to Text view and add some anchor text around the part you want to link. However I liked a more user friendly solution in which the source is stored within the Media Library itself.

I started out trying some plugins like media-credit and better image credits. However they added too much stuff around it, while I essentially wanted hyper-linked caption.

Luckily I came across a solution from Kaspars Dambis; How to Automatically Add Image Credit or Source URL to Photo Captions in WordPress. It behaved a bit strange with https links, but it was a solid base to work on. He created a filter for the ‘img_caption_shortcode’. You can read more about how Captions work in Justin Tadlock’s blog.

Solution

Most of the solution was already provided by Kaspars Dambis. I’ve added an extra field below the Source URL field in which you can fill in the credits. If you fill in the source URL only, the whole text in the Caption will change in a hyperlink to the source. If you fill in the credits field, that will be added to the  caption (after a ‘-‘ symbol) as a hyperlink.

To use this, just copy-paste the code to the functions.php of the theme (or child-theme) that you are using.

Result

Check the result of the plugin in my article on dynamic light (in Dutch only) at the Lumiflow website.

Code