如何使用DOM元素变量在GTM中添加AggregateRatingin?

时间:2017-06-19 07:55:33

标签: schema google-tag-manager json-ld

我用作自定义HTML标记的产品架构代码,用于在GTM中使用DOM变量实现产品架构。

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

如何在GTM中为AggregateRating变量(avgRating,ratingsCount)配置DOM元素变量。

这是标记

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

1 个答案:

答案 0 :(得分:1)

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