As you may have noticed or may be missed but WordPress currently doesn’t add Title attribute
to any post images. Title attributes mainly use for mouse hover Tooltip
which greatly improves readability for readers.
Not everyone loves Tooltip as many users don’t care about providing title and keep some random text for image title which may not be useful. In this tutorial we will go over WordPress hook to add Title Attribute automatically for all WordPress images.
Please take a look at below HTML screenshot first.
- wordpress add image title attribute
Just simply pool below code to your WordPress theme’s functions.php file.
// ~~~~~~~~~~~~~~~~~~~~~ Add Image Title - Crunchify.com Tips ~~~~~~~~~~~~~~~~~~~~~~~~ function crunchify_add_image_title( $html, $id ) { $crunchify_attach = get_post($id); if (strpos($html, "title=")) { return $html; } else { $crunchifyTitle = esc_attr($crunchify_attach->post_title); return str_replace('<img', '<img title="' . $crunchifyTitle . '" ' , $html); } } add_filter( 'media_send_to_editor', 'crunchify_add_image_title', 15, 2 ); function crunchify_add_image_title_gallery( $content, $id ) { $crunchify_title = get_the_title($id); return str_replace('<a', '<a title="' . esc_attr($crunchify_title) . '" ', $content); } add_filter('wp_get_attachment_link', 'crunchify_add_image_title_gallery', 10, 4);
And you are all set. Now onwards when you add an image to post you will see title attributes will be added automatically as you see in Insert image screen below.
Try hovering mouse pointer on below image to see tooltip 🙂
We hope you learn how to add Title attribute to images automatically by applying simple WordPress hook.
Note, above tricks will work for all newly added images. I would strongly recommend to add nice title to each images for user’s mouse hover Tooltip. Eventually better organized blog/site will lead you to the success you want one day.