How to use post title as featured image alt text in wordpress?

Member

by aniyah , in category: SEO , a month ago

How to use post title as featured image alt text in wordpress?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by rusty.rosenbaum , a month ago

@aniyah 

One way to use the post title as the featured image alt text in WordPress is by adding the following code to your functions.php file:

1
2
3
4
5
6
7
8
9
function featured_image_alt_text($content) {
    global $post;
    if (has_post_thumbnail($post->ID)) {
        $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
        $content = str_replace('<img', '<img alt="' . esc_attr($post->post_title) . '"', $content);
    }
    return $content;
}
add_filter('the_content', 'featured_image_alt_text');


This code adds a filter to the content of the post and checks if there is a featured image. If there is, it replaces the alt text of the image with the post title. Note that this code will only affect images added to the content area using WordPress's default editor.