Automatic jQuery accordion from header tags

I want it to be fairly easy for the post author to setup an accordion, based on header tags. So for example this:

<h3>Headline 1</h3>
<p>Content.. lorem ipsum</p>

<h3>Headline 2</h3>
<p>Content.. lorem ipsum</p>

<h3>Headline 3</h3>
<p>Content.. lorem ipsum</p>

would be converted to this (and so, accordion is activated)

Read More
<div class="accordion">
<h3>Headline 1</h3>
<div><p>Content.. lorem ipsum</p></div>
<h3>Headline 2</h3>
<div><p>Content.. lorem ipsum</p></div>
<h3>Headline 3</h3>
<div><p>Content.. lorem ipsum</p></div>
</div>

I’ve been using a setup with shortcodes — but this gets too complicated for the post author — so a more streamlined solution would be grand. Any ideas how I would go about doing this?

Related posts

Leave a Reply

1 comment

  1. You can use shortcode function to do this.

    function accordion_shortcode( $atts, $content = null ) {
       extract( shortcode_atts( array(
          'class' => 'accordion',
          ), $atts ) );
    
       return '<div class="' . esc_attr($class) . '">' . $content . '</div>';
    }
    
    add_shortcode( 'accordion', 'accordion_shortcode' );
    

    In editor you wrap your content:

    [accordion]
    <h3>Headline 1</h3>
    <p>Content.. lorem ipsum</p>
    
    <h3>Headline 2</h3>
    <p>Content.. lorem ipsum</p>
    
    <h3>Headline 3</h3>
    <p>Content.. lorem ipsum</p>
    [/accordion]