I am displaying a post gallery inside a custom post type, using the following in my single-custom.php template:

<?php echo do_shortcode('[gallery id="'.$post->ID.'" link="file" columns="5" orderby="menu_order"]'); ?>

One of the things included in the output is title="filename" in the <img> tag, like so:

<img width="150" height="150" src="http://mydomain.com/wp-content/uploads/DSC_0036-150x150.jpg" class="attachment-thumbnail" alt="DSC_0036" title="DSC_0036" />

I do not want to output the title attribute. Mostly, I don't want crappy filenames in the hover-over text, but there are hundreds of images and I'm not prepared to go into the Media Gallery and edit the title for each one. I'd prefer to also change the alt attribute to the post name, perhaps.

Is there a way to filter the gallery to output the post name in the alt and title attributes, instead of the filename?

2 Answers 2


The [gallery] shortcode is parsed by gallery_shortcode(), which calls wp_get_attachment_link(), which in turns calls wp_get_attachment_image(). This latter function writes the <img> tag with the title attribute. You're lucky, because the attributes are filtered through wp_get_attachment_image_attributes, so you can hook into that and remove the title.

To do this, you attach the hook before you call the shortcode and remove it after you did this. You can either do this in your template if it's a one-off, or, if you are more advanced, you "hijack" the [gallery] shortcode with your own function that adds the hook, calls the original gallery_shortcode() function, and removes the hook.

  • I tried using this in my functions.php: function replace_image_tag($html, $title){ $html = str_replace('title=""','title="Post"',$html); return $html; } add_filter('get_image_tag','replace_image_tag'); but it didn't change the output of the gallery at all? Feb 17, 2011 at 15:06
  • @Amanda: Where is get_image_tag() involved? You should filter wp_get_attachment_image_attributes, and remove the title element from the passed array.
    – Jan Fabry
    Feb 17, 2011 at 15:11
  • I was looking at core.trac.wordpress.org/browser/tags/3.0.5/wp-includes/… Thanks for the help, This works: function ergosport_gallery_filter( $attr ) { $attr['alt'] = "Ergosport Models"; $attr['title'] = "Click for a larger image"; return $attr; } add_filter( 'wp_get_attachment_image_attributes', 'ergosport_gallery_filter' ); Feb 17, 2011 at 16:38

This is very useful, thanks to the both of you. You can also add a copyright title attribute with the year automatically set: $attr['title'] = '© ' . date("Y") . ' Copyright ' . get_option('blogname');

  • You should be encoding the copyright symbol.
    – s_ha_dum
    Oct 3, 2015 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.