Michelle
Michelle

Reputation: 549

Code to add alt text to images in Wordpress

I have a Wordpress site and I have gone through the image gallery and added alt text to all images, however I've just learnt that this doesn't work retroactively so the alt text doesn't apply to any images on the site.

Does anyone know of a piece of code or a way to get the alt text to apply to all the images already on the site please?

I think we're missing quite a bit of SEO without the alt images.

Thanks!

Upvotes: 0

Views: 1891

Answers (1)

Nick
Nick

Reputation: 356

This should work. If the image as no alt text set, it will be set based on the title of the post the image is attached to:

function add_alt_to_images_if_missing( $attr, $attachment = null ) {
    if($attr['alt']==''){
        $attr['alt']=trim( strip_tags( $attachment->post_title ) );
    }
    return $attr;
}
add_filter( 'wp_get_attachment_image_attributes','add_alt_to_images_if_missing', 10, 2 );

Upvotes: 2

Related Questions