Image alt tag (attribute) is useful because it describes your images and make users easier to find relevant content while searching on Google and other search engines.
If you run a WordPress website, you can of course add alt tags manually for each image but if you have a lot of content you will probably want an easy way to automatically set alt attributes at once. This particular example will show how you can change all your featured image (thumbnail) alt tags to its specific post title.
Introducing post_thumbnail_html WordPress filter hook
We are just using few lines of code in post_thumbnail_html WordPress filter hook. Note that your image alt tags won’t be physically changed in media library, the snippet will just modify HTML output on the frontend of your site.
1 2 3 4 5 6 7 8 9 10 11 12 | /* Register callback function for post_thumbnail_html filter hook */ add_filter( 'post_thumbnail_html', 'meks_post_thumbnail_alt_change', 10, 5 ); /* Function which will replace alt atribute to post title */ function meks_post_thumbnail_alt_change( $html, $post_id, $post_thumbnail_id, $size, $attr ) { $post_title = get_the_title(); $html = preg_replace( '/(alt=")(.*?)(")/i', '$1'.esc_attr( $post_title ).'$3', $html ); return $html; } |
That’s all folks! You just need to paste this snippet somewhere inside your theme functions.php file. Feel free to try and give us a feedback.