Mourin Bably
Mourin Bably

Reputation: 123

How to add AggregateRatingin in GTM using DOM element Variables?

The Product Schema code that i am using as a custom HTML tag for implementing product schema using DOM variables in GTM..

<script>
var jsonData = {
  "@context": "http://schema.org",
  "@type": "Product",
  "name": {{productName}},
  "image": {{productImg}},
  "url": {{Page URL}},
  "aggregateRating": {
    "@type": "AggregateRating",
"ratingValue": {{avgRating}},
    "reviewCount": {{ratingsCount}},
  }
  }

  var script = document.createElement('script');
  script.type = 'application/ld+json';
  script.text = JSON.stringify(jsonData);
  $("head").append(script);
</script>

how can i configure the DOM element variable for AggregateRating Variables (avgRating, ratingsCount) in GTM.

here is the Markup

<div class="woocommerce-product-rating">
        <div class="star-rating">
            <span style="width:100%">
                <strong class="rating">5.00</strong> out of <span>5</span>              based on <span class="rating">1</span> customer rating          </span>
        </div>
        <a href="#reviews" class="woocommerce-review-link" rel="nofollow">(<span class="count">1</span> customer review)</a>    </div>

Upvotes: 0

Views: 176

Answers (1)

Victor Leontyev
Victor Leontyev

Reputation: 8736

You need to create two variables in GTM

1) Go to Variables->User-Defined Variables->New->Custom Javascript

2) Create variable with name ProductAvgRating and JS code:

function () {
  try {
    return parseFloat(document.querySelector('.woocommerce-product-rating strong.rating').innerText);
  }
  catch(e) {return 0;}
}

2) Create variable with name ProductRatingsCount and JS code:

function () {
  try {
    return parseInt(document.querySelector('.woocommerce-product-rating span.rating').innerText);
  }
  catch(e) {return 0;}
}

And then change your html tag like that:

<script>
var jsonData = {
  "@context": "http://schema.org",
  "@type": "Product",
  "name": {{productName}},
  "image": {{productImg}},
  "url": {{Page URL}},
  "aggregateRating": {
    "@type": "AggregateRating",
"ratingValue": {{ProductAvgRating}},
    "reviewCount": {{ProductRatingsCount}},
  }
  }

  var script = document.createElement('script');
  script.type = 'application/ld+json';
  script.text = JSON.stringify(jsonData);
  $("head").append(script);
</script>

P.S. You didn't ask about productName and productImg variables, i guess you already have it

Upvotes: 1

Related Questions