/**
* Generates and outputs FAQ schema in JSON-LD format for posts and pages.
*
* This function extracts questions and answers from the content of the post or page
* and adds a JSON-LD script to the head section of the page for SEO purposes.
*/
function generate_faq_schema() {
// Check if we are on a singular post or page, are in the loop, and this is the main query
if (is_singular() && in_the_loop() && is_main_query()) {
global $post;
// Get the content of the post or page
$content = $post->post_content;
// Initialize DOMDocument to parse HTML content
$doc = new DOMDocument();
// Load the HTML content into DOMDocument with UTF-8 encoding
@$doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
// Initialize an array to store the FAQ schema
$faqData = [
"@context" => "https://schema.org",
"@type" => "FAQPage",
"mainEntity" => []
];
// Create a DOMXPath object to navigate and query the DOM
$xpath = new DOMXPath($doc);
// Query all elements with the class "accordion-item"
$items = $xpath->query('//div[contains(@class, "accordion-item")]');
// Iterate through each accordion item
foreach ($items as $item) {
// Find the question and answer elements within the accordion item
$questionNode = $xpath->query('.//div[contains(@class, "title")]', $item);
$answerNode = $xpath->query('.//div[contains(@class, "accordion-content-wrapper")]', $item);
// Check if both question and answer nodes are present
if ($questionNode->length > 0 && $answerNode->length > 0) {
// Extract the text content and trim whitespace
$question = trim($questionNode->item(0)->textContent);
$answer = trim($answerNode->item(0)->textContent);
// Add the question and answer to the FAQ schema array
$faqData['mainEntity'][] = [
"@type" => "Question",
"name" => $question,
"acceptedAnswer" => [
"@type" => "Answer",
"text" => $answer
]
];
}
}
// Convert the PHP array to a JSON-LD string with pretty print and unescaped slashes
$jsonLD = json_encode($faqData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
// Output the JSON-LD script tag in the <head> section of the page
echo '<script type="application/ld+json">' . $jsonLD . '</script>';
}
}
// Hook the function to 'wp_head' action to add schema to the head of the page
add_action('wp_head', 'generate_faq_schema');
Comments