FAQ Structured Data From Details Blocks
Turns every Details block (summary and hidden text) in a post or page into a question and answer in FAQPage JSON-LD, with nothing extra to fill in.
Opens WPIDE on
Code
add_action( 'wp_head', function () {
if ( ! is_singular() ) {
return;
}
$post = get_queried_object();
if ( ! $post instanceof WP_Post || ! has_block( 'core/details', $post ) ) {
return;
}
$questions = array();
$html_of = function ( $blocks ) use ( &$html_of ) {
$html = '';
foreach ( $blocks as $block ) {
$html .= $block['innerHTML'] . ' ' . $html_of( $block['innerBlocks'] );
}
return $html;
};
$walk = function ( $blocks ) use ( &$walk, &$questions, $html_of ) {
foreach ( $blocks as $block ) {
if ( 'core/details' !== $block['blockName'] ) {
if ( ! empty( $block['innerBlocks'] ) ) {
$walk( $block['innerBlocks'] );
}
continue;
}
if ( ! preg_match( '#<summary[^>]*>(.*?)</summary>(.*)#is', (string) $block['innerHTML'], $m ) ) {
continue;
}
$question = trim( wp_strip_all_tags( $m[1] ) );
$answer = trim( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $m[2] . ' ' . $html_of( $block['innerBlocks'] ) ) ) );
if ( '' !== $question && '' !== $answer ) {
$questions[] = array( '@type' => 'Question', 'name' => $question, 'acceptedAnswer' => array( '@type' => 'Answer', 'text' => $answer ) );
}
}
};
$walk( parse_blocks( $post->post_content ) );
if ( $questions ) {
echo '<script type="application/ld+json">' . wp_json_encode( array( '@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => $questions ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG ) . "</script>\n";
}
} );
Notes
Google now shows FAQ rich results mainly for authoritative health and government sites, but other search and AI tools still read the markup.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.