How to Add a Title to Featured Images in GeneratePress

Quick Summary

  • Filter wp_get_attachment_image_attributes to set each featured image's title attribute from its Media Library title, which then shows on hover.
  • Written for GeneratePress, the snippet works in other themes too, because the_post_thumbnail() builds images through wp_get_attachment_image().
  • Every image built with wp_get_attachment_image() gets a title, not only featured images, and a title doesn't replace alt text.

This snippet adds a title attribute to featured images, so the image’s title shows as a tooltip when a visitor hovers over it. It was written for the GeneratePress theme, but it works with other themes too, because it hooks into the WordPress function that builds image tags.

Add it to your child theme’s functions.php or a code snippets plugin.

PHP
add_filter( 'wp_get_attachment_image_attributes', 'tl_add_img_title', 10, 2 );
// Add title attribute to featured image
function tl_add_img_title( $attr, $attachment = null){
	$attr['title'] = get_post( $attachment->ID )->post_title;
	return $attr;
}

The wp_get_attachment_image_attributes filter runs whenever WordPress builds an <img> tag with wp_get_attachment_image(), which is also what the_post_thumbnail() uses for featured images. It receives the tag’s attributes as an array and the attachment post. tl_add_img_title() sets $attr['title'] to the attachment’s title and returns the array. If filters are new to you, see how WordPress action and filter hooks work.

  • The title comes from the Title field in the Media Library, which is often just the file name. Edit it if you want a readable tooltip.
  • The filter isn’t limited to featured images: any image that goes through wp_get_attachment_image() gets a title too.
  • A title attribute doesn’t replace alt text. Keep filling in the Alternative Text field for screen readers.
Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More