Using Google Tag Manager to Dynamically Generate Schema/JSON-LD Tags

2 min read
Curated from moz.com →

One of the biggest takeaways from SearchFest in Portland earlier this year was the rapidly rising importance of semantic search and structured data — in particular Schema.org. And while implementing Schema used to require a lot of changes to your site’s markup, the JSON-LD format has created a great alternative to adding microdata to a page with minimal code.

What was even more exciting was the idea that you could use Google Tag Manager to insert JSON-LD into a page, allowing you to add Schema markup to your site without having to touch the site’s code directly (in other words, no back and forth with the IT department).

Trouble is, while it seemed like Tag Manager would let you insert a JSON-LD snippet on the page no problem, it didn’t appear to be possible to use other Tag Manager features to dynamically generate that snippet. Tag Manager lets you create variables by extracting content from the page using either CSS selectors or some basic JavaScript. These variables can then be used dynamically in your tags (check out Mike’s post on semantic analysis for a good example).

So if we wanted to grab that page URL and pass it dynamically to the JSON-LD snippet, we might have tried something like this:

Meaning that if you wanted to use GTM to add the the BlogPosting Schema type to each of your blog posts, you would have to create a different tag and trigger (based on the URL) for each post. Not exactly scalable.

But, with a bit of experimentation, I’ve figured out a little bit of JavaScript magic that makes it possible to extract data from the existing content on the page and dynamically create a valid JSON-LD snippet.

The reason why our first example doesn’t work is because Tag Manager replaces each variable with a little piece of JavaScript that calls a function — returning the value of whatever variable is called.

Continue Reading

Enjoyed this summary? Read the complete article at the source:

Continue at moz.com →

Yves Mulkers

Yves Mulkers is the founder of 7wData and a widely followed voice in the data and AI community. He curates the 7wData and AI Beat newsletters, reaching hundreds of thousands of data and AI professionals, and writes on data strategy, analytics, AI, and the evolving data ecosystem.