Adding the Title Attribute to Image Tags in WordPress

I don’t find the title attribute provides a whole lot of value to images. WordPress sets the title automatically to the filename of the image, and that’s not typically the correct content for such an attribute.

SEO? Not likely. This attribute is rife with potential to try and stuff keywords into a page that aren’t relevant, and I highly doubt (and haven’t found much evidence supporting) Google is looking at these titles and assigning rank based on what’s in there.

That said, if you’d like to add titles to all of your Featured Images (called via the_post_thumbnail()) and those added via the Add Media button in the WordPress Post Editor, you can add the following code to your functions.php.

Note that for images added directly to the post, this will not update old images, just work for all future images added in that way. It will be automatically applied to any featured images, though, old or new.

// set the title attribute on images inserted via the editor, and then those created as featured images
function inserted_image_titles( $html, $id ) {
$attachment = get_post($id);
$thetitle = $attachment->post_title;
return str_replace('<img', '<img title="' . $thetitle . '" ' , $html);
}
add_filter( 'media_send_to_editor', 'inserted_image_titles', 15, 2 );
function featured_image_titles($attr, $attachment = null){
$attr['title'] = get_post($attachment->ID)->post_title;
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'featured_image_titles', 10, 2);

Up Next: My Approach to Responsive Design