Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Define the class for your howto object here
- // They should be marked up in a consistent manner.
- var parentClass = 'howto_block'
- var imageClass = 'howto_image';
- var nameClass = 'howto_name';
- var descriptionClass = 'howto_description';
- var stepClass = 'howto_step';
- // Output schema to console. Set to `false` if adding via tag manager.
- var logOutput = true;
- (function(){
- var parent = document.querySelector('.' + parentClass.replace('.', ''))
- // Build Data
- const howto_image = parent.querySelector('.' + imageClass.replace('.', '')).href;
- const howto_name = parent.querySelector('.' + nameClass.replace('.', '')).textContent;
- const howto_desc = parent.querySelector('.' + descriptionClass.replace('.', '')).textContent;
- const howto_steps = parent.querySelectorAll('.' + stepClass.replace('.', ''));
- if (howto_steps.length && typeof howto_name !== 'undefined'){
- var data = {
- "@context": "https://schema.org",
- "@type": "HowTo",
- "name": howto_name,
- "step": []
- };
- var img_data = {
- "@type": "ImageObject",
- "url": null
- };
- buildStep = (s, i) => {
- var item = {
- "@type": "HowToStep",
- "name": null,
- "url": null
- };
- item['name'] = s.textContent;
- const step_img = s.querySelector('img').href;
- if (typeof step_img !== 'undefined') {
- item['image'] = step_img;
- }
- item['url'] = window.location.href.split('#')[0] + "#step" + (i+1);
- return item;
- }
- if (typeof howto_image !== 'undefined') {
- img_data['url'] = howto_image;
- data['image'] = img_data;
- }
- if (typeof howto_desc !== 'undefined') {
- data['description'] = howto_desc;
- }
- data['step'] = howto_steps.map(function(s, i){return buildStep(s, i)});
- var script = document.createElement('script');
- script.type = "application/ld+json";
- script.innerHTML = JSON.stringify(data);
- document.getElementsByTagName('head')[0].appendChild(script);
- if (logOutput){
- console.log(script.outerHTML);
- }
- }else{
- console.error('Howto schema could not be generated. Steps or name not defined.')
- }
- })(document);
Add Comment
Please, Sign In to add comment