FAQ Accordion Shortcode With Schema
Adds a [faq_list] shortcode that shows FAQ posts as accessible collapsible questions and adds FAQPage structured data for them.
Opens WPIDE on
Code
add_shortcode( 'faq_list', function ( $atts ) {
$atts = shortcode_atts( array( 'group' => '', 'limit' => 50, 'schema' => 'yes' ), $atts, 'faq_list' );
if ( ! post_type_exists( 'faq' ) ) {
return '';
}
$args = array(
'post_type' => 'faq',
'posts_per_page' => min( 100, absint( $atts['limit'] ) ),
'orderby' => array( 'menu_order' => 'ASC', 'title' => 'ASC' ),
'no_found_rows' => true,
);
if ( $atts['group'] && taxonomy_exists( 'faq_group' ) ) {
$args['tax_query'] = array( array( 'taxonomy' => 'faq_group', 'field' => 'slug', 'terms' => sanitize_title( $atts['group'] ) ) );
}
$faqs = get_posts( $args );
if ( ! $faqs ) {
return '';
}
$html = '<div class="faq-list">';
$schema = array( '@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => array() );
foreach ( $faqs as $faq ) {
$answer = wp_kses_post( wpautop( do_shortcode( $faq->post_content ) ) );
$html .= '<details class="faq-item"><summary>' . esc_html( get_the_title( $faq ) ) . '</summary><div class="faq-answer">' . $answer . '</div></details>';
$schema['mainEntity'][] = array(
'@type' => 'Question',
'name' => wp_strip_all_tags( get_the_title( $faq ) ),
'acceptedAnswer' => array( '@type' => 'Answer', 'text' => trim( wp_strip_all_tags( $answer, true ) ) ),
);
}
$html .= '</div>';
if ( 'no' !== $atts['schema'] ) {
$html .= '<script type="application/ld+json">' . wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG ) . '</script>';
}
return $html;
} );
Notes
Works with the FAQ post type snippet. Filter by group with group="billing", or turn the schema off with schema="no".
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.