skip to Main Content

After doing some research I found out that image titles and alt matters a lot for SEO and changing each image title and alt will take too long.

I found this code here but it did not affect the current images.

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;
}

2

Answers


  1. You can try woocommerce_gallery_image_html_attachment_image_params filter for the customization. Check following example. It fetches the product title and assigns it to the alt and title attribute of the image. Note: This only works in product single page.

    add_filter( 'woocommerce_gallery_image_html_attachment_image_params','wpso_customize_single_product_image' );
    
    function wpso_customize_single_product_image( $details ) {
        global $product;
        $details['alt'] = $details['title'] = get_the_title( $product->get_id() );
        return $details;
    }
    
    Login or Signup to reply.
  2. Log in to your Phpmyadmin, select your database and run this query to update images titles:

    UPDATE wp_posts as a
    LEFT JOIN wp_postmeta as b ON a.ID = b.meta_value
    LEFT JOIN wp_posts as c ON b.post_id = c.ID
    SET a.post_title = c.post_title
    WHERE a.post_type = 'attachment'
    AND a.post_mime_type = 'image/jpeg'
    AND b.meta_key = '_thumbnail_id'
    AND c.post_type = 'product'
    

    … and this SQL query to update images alts:

    UPDATE wp_postmeta as z 
    LEFT JOIN wp_posts as a ON z.post_id = a.ID 
    LEFT JOIN wp_postmeta as b ON a.ID = b.meta_value 
    LEFT JOIN wp_posts as c ON b.post_id = c.ID 
    SET z.meta_value = c.post_title 
    WHERE z.meta_key = '_wp_attachment_image_alt' 
    AND a.post_type = 'attachment' 
    AND a.post_mime_type = 'image/jpeg' 
    AND b.meta_key = '_thumbnail_id' 
    AND c.post_type = 'product'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search