# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [SEO](https://wpide.com/library/category/seo/)
- Tags: faq, schema, shortcode
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/faq-shortcode-with-schema/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "FAQ Shortcode With FAQ Schema" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
