Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add FAQ ld json to article pages #313

Merged
merged 6 commits into from
Jun 14, 2024
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions cigaradvisor/scripts/linking-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,57 @@ 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)) {
bstopp marked this conversation as resolved.
Show resolved Hide resolved
addOrUpdateCollection();
window.addEventListener('hashchange', addOrUpdateCollection);
} else if (getCategory(window.location.pathname)) {
addFAQLdJson();
}
}