4

Adding alt tag information to every product photo is a lot of work. We always just copy and paste our product title into the image alt tags.

I figured since all the information is there; there must be a way to do this automatically.

Question: How do you apply a woocommerce product's TITLE as all the ALT TAGS for images used with that product.

Any help is much appreciated!

1

3 Answers 3

9

This is what you need, taken from - https://stackoverflow.com/questions/27087772/how-can-i-change-meta-alt-and-title-in-catalog-thumbnail-product-thumbnail

add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);

function change_attachement_image_attributes( $attr, $attachment ){
    // Get post parent
    $parent = get_post_field( 'post_parent', $attachment);

    // Get post type to check if it's product
    $type = get_post_field( 'post_type', $parent);
    if( $type != 'product' ){
        return $attr;
    }

    /// Get title
    $title = get_post_field( 'post_title', $parent);

    $attr['alt'] = $title;
    $attr['title'] = $title;

    return $attr;
}
1
  • 1
    How would I do this for product thumbnails too? E.g. on the shop main site where the products are listed Mar 25, 2018 at 16:14
5

For anyone searching, I would recommend editing the code above so if a product image already has an alt tag do not override it with the post title. This way you can still add product image titles if necessary.

add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes( $attr, $attachment ) {
// Get post parent
$parent = get_post_field( 'post_parent', $attachment);

// Get post type to check if it's product
$type = get_post_field( 'post_type', $parent);
if( $type != 'product' ){
    return $attr;
}

/// Get title
$title = get_post_field( 'post_title', $parent);

if( $attr['alt'] == ''){
    $attr['alt'] = $title;
    $attr['title'] = $title;
}

return $attr;
}
1
  • Assume these go in the functions.php file? Thanks
    – landed
    Oct 17, 2018 at 13:41
4

If anyone is looking for a fast and easy way to use product titles as product image alt tags, I recommend the Woo Image SEO plugin.
The plugin can also handle the creation of title attributes.
Additionally, you can customize the attributes by including the product's category and tag in any order. enter image description here

2
  • Very cool Danail! Ill check it out
    – Patrick
    Dec 24, 2018 at 21:15
  • This works like a charm. Rank Math SEO used to do this but their latest versions amazingly cannot achieve it anymore. Thanks for this. The functions above also do not work with latest Woocommerce for some reason.
    – MitchellK
    Sep 21, 2021 at 9:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.