Reputation: 209
I wasn't able to respond to the original posting as it was closed.
The code snippet provided in the link works; however it changes my logo alt text in the header to the alt text of the first product image.
Can anyone advise how can I change this behavior?
Upvotes: 1
Views: 7595
Reputation: 21
The easiest way to do it is to set the ALT tags of your logo in the Media, then use the script to check if the ALT tag is empty and only replace it if it is. This can be also applied to other images that you don't want the Alt tags to be overridden. Another thing that was giving me issues was product titles that had quotes as the alt tag is enclosed by quotes, in my case I replaced them with the word in. for inches, just something to be aware if you have quotes in the titles, you have to replace them based on your application.
//This will add in the product title to the alt tag on the shop page.
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;
}
if($attr['alt']=='') {
// Get title and remove any double quotes
$title = str_replace('"',' in.', get_post_field( 'post_title', $parent));
$attr['alt'] = $title;
$attr['title'] = $title;
}
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
Upvotes: 0
Reputation: 119
add to function.php
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes($attr, $attachment) {
global $post;
if ($post->post_type == 'product') {
$title = $post->post_title;
$attr['alt'] = $title;
$attr['title'] = $title;
}
return $attr;
}
Upvotes: 1
Reputation: 209
This is the correct code snippet
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;
}
if ( isset( $attr['class'] ) && 'custom-logo' === $attr['class'] ) {
return $attr;
}
/// Get title
$title = get_post_field( 'post_title', $parent);
$attr['alt'] = $title;
$attr['title'] = $title;
return $attr;
}
Upvotes: 3
Reputation: 4243
This will add in the product title to the alt tag on the shop page.
function modify_shop_product_image ( $img, $product, $size, $attr, $placeholder ) {
$alt_tag = 'alt=';
$pos = stripos( $img, 'alt=' ) + strlen( $alt_tag ) + 1;
return substr_replace($img, $product->get_name(), $pos, 0);
}
add_action( 'woocommerce_product_get_image', 'modify_shop_product_image', 10, 5 );
Upvotes: 2