From f22f29217617965051bbe8f97ee533c139a06f18 Mon Sep 17 00:00:00 2001 From: bdeffleyfamous <38252554+bdeffleyfamous@users.noreply.github.com> Date: Fri, 14 Jun 2024 13:50:27 -0400 Subject: [PATCH] Add FAQ ld json to article pages (#313) * Add FAQ ld json to article pages * code formatting * code formatting * only call faqjson if it is a blog page * assign getCategory to a variable * refactor function --- cigaradvisor/scripts/linking-data.js | 54 ++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/cigaradvisor/scripts/linking-data.js b/cigaradvisor/scripts/linking-data.js index 68cb1df..24e2172 100644 --- a/cigaradvisor/scripts/linking-data.js +++ b/cigaradvisor/scripts/linking-data.js @@ -83,12 +83,60 @@ function addBlogPosts() { addLdJsonScript(document.querySelector('head'), ldjson); } +/** + * Determines if the page contains a FAQ section and writes the LD JSON to the head + */ +function addFAQLdJson() { + const contentDivs = document.querySelectorAll('.default-content-wrapper'); + // find the content div that contains a FAQ + for (let i = 0; i < contentDivs.length; i += 1) { + let isFAQPage = false; + const h2Elements = contentDivs[i].getElementsByTagName('h2'); + // Does the div contain a faq section? + for (let j = 0; j < h2Elements.length; j += 1) { + if (h2Elements[j].id.includes('frequently-asked-questions')) { + isFAQPage = true; + } + } + if (isFAQPage) { + const ldjson = { + '@context': 'http://schema.org/', + '@type': 'FAQPage', + mainEntity: [], + }; + // questions should be in the h3 elements, with the answers in the following element + const h3Elements = contentDivs[i].getElementsByTagName('h3'); + for (let k = 0; k < h3Elements.length; k += 1) { + const QAEntity = { + '@type': 'Question', + name: h3Elements[k].textContent, + acceptedAnswer: {}, + }; + if (h3Elements[k].nextElementSibling) { + QAEntity.acceptedAnswer = { + '@type': 'Answer', + text: h3Elements[k].nextElementSibling.textContent, + }; + // add question only if we found the answer + ldjson.mainEntity.push(QAEntity); + } + } + addLdJsonScript(document.querySelector('head'), ldjson); + } + } +} + export default function addLinkingData() { addOrg(document.querySelector('head')); if (window.location.pathname === '/cigaradvisor') { addBlogPosts(); - } else if (window.location.pathname === getCategory(window.location.pathname)) { - addOrUpdateCollection(); - window.addEventListener('hashchange', addOrUpdateCollection); + } else { + const category = getCategory(window.location.pathname); + if (window.location.pathname === category) { + addOrUpdateCollection(); + window.addEventListener('hashchange', addOrUpdateCollection); + } else if (category) { + addFAQLdJson(); + } } }