Product Name as Alt Text for WooCommerce Images Without One
When a product image in the shop, on category pages or on the product page has no alternative text, uses the product name instead of leaving it empty.
Opens WPIDE on
Code
add_filter( 'wp_get_attachment_image_attributes', function ( $attr, $attachment ) {
if ( '' !== trim( (string) ( isset( $attr['alt'] ) ? $attr['alt'] : '' ) ) || ! function_exists( 'wc_get_product' ) ) {
return $attr;
}
$post_id = get_the_ID();
if ( $post_id && 'product' === get_post_type( $post_id ) ) {
$attr['alt'] = wp_strip_all_tags( get_the_title( $post_id ) );
} elseif ( $attachment && $attachment->post_parent && 'product' === get_post_type( $attachment->post_parent ) ) {
$attr['alt'] = wp_strip_all_tags( get_the_title( $attachment->post_parent ) );
}
return $attr;
}, 20, 2 );
Notes
Images with their own alt text in the media library are not changed.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.