FAQ Shortcode With FAQ Schema
Adds a [faq] shortcode for collapsible questions and answers, and outputs matching FAQPage structured data for every question on the page.
Opens WPIDE on
Code
$wpide_faq_items = array();
add_shortcode( 'faq', function ( $atts, $content = '' ) use ( &$wpide_faq_items ) {
$atts = shortcode_atts( array( 'question' => '' ), $atts, 'faq' );
$question = trim( $atts['question'] );
if ( '' === $question || '' === trim( (string) $content ) ) {
return '';
}
$answer = wpautop( do_shortcode( wp_kses_post( (string) $content ) ) );
if ( is_singular() ) {
$wpide_faq_items[ md5( $question ) ] = array( $question, $answer );
}
return '<details class="wpide-faq" style="margin:0 0 .75em;padding:.75em 1em;border:1px solid rgba(0,0,0,.15);border-radius:4px;"><summary style="cursor:pointer;font-weight:600;">' . esc_html( $question ) . '</summary><div style="margin-top:.5em;">' . $answer . '</div></details>';
} );
add_action( 'wp_footer', function () use ( &$wpide_faq_items ) {
if ( ! $wpide_faq_items ) {
return;
}
$allowed = array( 'p' => array(), 'br' => array(), 'a' => array( 'href' => array() ), 'strong' => array(), 'em' => array(), 'ul' => array(), 'ol' => array(), 'li' => array() );
$data = array(
'@context' => 'https://schema.org',
'@type' => 'FAQPage',
'mainEntity' => array(),
);
foreach ( $wpide_faq_items as $item ) {
$data['mainEntity'][] = array(
'@type' => 'Question',
'name' => wp_strip_all_tags( $item[0] ),
'acceptedAnswer' => array(
'@type' => 'Answer',
'text' => trim( wp_kses( $item[1], $allowed ) ),
),
);
}
echo '<script type="application/ld+json">' . wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG ) . "</script>\n";
} );
Notes
Example: [faq question="Do you ship abroad?"]Yes, to most countries.[/faq]. Google now shows FAQ rich results mainly for authoritative sites, but the markup still describes your content.
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.