How to create a dynamic FAQ scheme in Wordpress?

Viewed 76

We would like to have a dynamic FAQ-scheme in Wordpress. Now I am familiar with the scheme.org and how to do it manually. So practically filling the scheme manually and fire it with GTM for example. However, we would prefer dynamic of course.

I walked into a piece of content which seem to help, but I can't make it work. We used. the code below:

    (function(){
    var data = {
    "@context":"https://schema.org",
  "@type":"FAQPage",
  "mainEntity":[]
}
    for (i = 0; i < document.querySelectorAll('CSS_Selector_of_Question').length; i++) 
{
        data.mainEntity.push({
            "@type":"Question",
            "name":document.querySelectorAll('CSS_Selector_of_Question')[i].innerText,
            "acceptedAnswer": {
                "@type": "Answer",
                "text":document.querySelectorAll('CSS_Selector_of_Answer')[i].innerText
            }
        });
    };
  var script = document.createElement('script');
  script.type = "application/ld+json";
  script.innerHTML = JSON.stringify(data);
  document.getElementsByTagName('head')[0].appendChild(script);
})(document);

In this code we replaced 'CSS_Selector_of_Answer' and 'CSS_Selector_of_Question' by classes we gave to the answer and question in our css. However, no result unfortunately. The page were we tested this is: https://bconnect.chat/vacatures/chat-operator/

At the moment the tag is not firing for your information.

Is there anyone able to help?

1 Answers

it's selecting all entities anew on each iteration. instead, try selecting faq containers, and then iterate them and extract q&a values of each

so, select all faqRowText, and then extract faqquestion and faqanswer values accordingly:

try this code:

(function() {
   var data = {
     "@context": "https://schema.org",
     "@type": "FAQPage",
     "mainEntity": []
   }

   Array.from(document.querySelectorAll('.faqRowText')).map(function(row){

     data.mainEntity.push({
       "@type": "Question",
       "name": row.querySelector('.faqquestion').innerText,
       "acceptedAnswer": {
         "@type": "Answer",
         "text": row.querySelector('.faqanswer').innerText
       }
     });    

   });

   var script = document.createElement('script');
   script.type = "application/ld+json";
   script.innerHTML = JSON.stringify(data);
   document.getElementsByTagName('head')[0].appendChild(script);
 })(document);
Related