Halloween Sale 15% off Ends in See the plans
PHP

Block Pattern: FAQ With Expandable Answers

Adds an FAQ pattern built from core Details blocks, so visitors click a question to reveal its answer, with no plugin and no JavaScript.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'init', function () {
    if ( ! function_exists( 'register_block_pattern' ) ) {
        return;
    }

    if ( ! WP_Block_Pattern_Categories_Registry::get_instance()->is_registered( 'wpide-sections' ) ) {
        register_block_pattern_category( 'wpide-sections', array( 'label' => 'Site Sections' ) );
    }

    $questions = array(
        'How long does delivery take?'    => 'Most orders arrive within 3 to 5 working days.',
        'Can I change my order?'          => 'Yes, reply to your confirmation email within 24 hours and we will update it.',
        'Do you ship internationally?'    => 'We ship to most countries in Europe and North America.',
        'What is your returns policy?'    => 'Return any unused item within 30 days for a full refund.',
    );

    $items = '';
    foreach ( $questions as $question => $answer ) {
        $items .= '<!-- wp:details --><details class="wp-block-details"><summary>' . esc_html( $question ) . '</summary><!-- wp:paragraph --><p>' . esc_html( $answer ) . '</p><!-- /wp:paragraph --></details><!-- /wp:details -->';
    }

    register_block_pattern( 'wpide/faq-details', array(
        'title'       => 'FAQ: expandable answers',
        'description' => 'Frequently asked questions using Details blocks.',
        'categories'  => array( 'wpide-sections' ),
        'keywords'    => array( 'faq', 'questions', 'accordion' ),
        'content'     => '<!-- wp:group {"layout":{"type":"constrained"}} --><div class="wp-block-group"><!-- wp:heading --><h2 class="wp-block-heading">Frequently asked questions</h2><!-- /wp:heading -->' . $items . '</div><!-- /wp:group -->',
    ) );
} );

Notes

Add or remove questions by duplicating a Details block in the editor.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.