WooCommerce - microdata on Product Image

I've been tweaking an eCommerce site recently which is built on WordPress and WooCommerce to make it more SEO friendly.

The chosen theme has taken kept pretty close to the default implementation of the WooCommerce Product pages with a few small tweaks here and there.

However, I recently noticed that the main product image was coming up in the google image searches with the title "Zoom" and so I started to dig into the code to find out why.


WooCommerce

It turned out that the base version of WooCommerce (and I know I'm running one version behind) wraps the Product Image in a A href where the itemprop="image" is placed on the A tag.  this means that any text in the A tag is considered part of title image by google (or at least relevant text) and in this case, that is a DIV with the word Zoom in it!

Get_the_post_thumbnail

In single-product/product-image.php you should find the code that creates the image and in here I found that it was using the standard WordPress function get_the_post_thumbnail  to create the image - which makes adding the itemprop attribute a bit more tricky.

After investigating appropriate hooks and filters, in the end, I decided just to pass the output from get_the_post_thumbnail into a custom function and use this function to add  the itemprop attribute.


In single-product/product-image.php change the echo get_the_post_thumbnail ... to something more like this


    // note: keep your existing parameters to get_the_post_thumbnal - don't copy mine, they are theme specific...
     echo cb_add_itemprop_image(get_the_post_thumbnail( $post->ID, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ) ) );

and then in your theme's function.php add the function as follows:-

/*
 * Add itemprop='image' to an image
 */
function cb_add_itemprop_image($image) {
    $dom = new DOMDocument();
    $dom->loadHTML($image);
    //echo "";
    foreach ($dom->getElementsByTagName('img') as $item) {
  $item->setAttribute('itemprop', 'image');
  $return=$dom->saveHTML($item);
  $return2=addslashes($return);
  //echo "";
  return $return;
    }
}

This function takes the image tag html and converts it into a DOM element. Then for each 'IMG' node it adds the itemprop='image' attribute. In fact, it exists on the first occurrence as I'm only expecting one!

I hope this helps you ... based on WooCommerce version 2.0.20




Did you know you can hire me?

I take on projects of all sizes. From Consulting to large Development Projects.

If you're starting a new Yii project and would like some help to get setup and running or you need some help with a particular module or you just need someone to develop the whole dang thing, then just ask ...


Leave a Comment

twitterfacebookgooglelinkedin https://me.yahoo.com