Replacing titles with captions in WordPress gallery image links

Recently I have installed a colorbox plugin onto this blog for image galleries.

This plugin overrides the default behaviour of an image gallery and replaces individual image pages with a simple in-page pop up of the image. It works quite nicely, however, one problem I have had is that it extracts the title attribute from the former page links rather than the caption of the image that it is displaying.

I have spent the last few days trying to figure out a way to get the behaviour I want out of the plugin. However, this has been much more difficult that expected, the code that generates the galleries in WordPress is buried deep in the code and isn’t as straight-forward as replacing title=getTitle with title=getCaption. Trying to edit the behaviour of the jquery on the colorbox plugin isn’t an option either as it is heavily optimised. And updating every database row to replace the title with the caption also isn’t very practical.

Instead the simple hack below will achieve what I want. It isn’t pretty and I am still looking for a better solution, but in the meantime after the page has been rendered the jquery quickly looks for galleries and replaces the titles in any links with the alt text from the image. This means that when an image loads in the colorbox it displays with a caption.

<script type="text/javascript">
jQuery(document).ready(function($) {
 $('.gallery img').each(function() { 
  $(this).parent().attr('title',$(this).attr('alt')); 
 });
});
</script>