Twitter Bootstrap Use Collapse in Custom Post Type

The script

First you have to enqueue the script. We conditionally load it only for your custom post type and its archive(s).

// in your functions.php
function wpse69274_enqueue_tbs_collapse()
{
    if (
        ! is_post_type_archive()
        AND 'YOUR_POST_TYPE' !== get_post_type()
    )
        return;

    wp_enqueue_script(
         'tbs-collapse'
        ,get_stylesheet_directory_url().'path/to/your/collapse.js';
        ,array( 'jquery' )
        ,filemtime( get_stylesheet_directory().'path/to/your/collapse.js' )
        ,true
    );
}
add_action( 'wp_enqueue_scripts', 'wpse69274_enqueue_tbs_collapse' );

The MarkUp

Now we need to add the proper MarkUp. The targets get marked by using the actual the_ID() of the currently looped post.

<div class="container">
<div class="accordion" id="accordion">
    <?php
    global $wp_query;
    if ( have_posts() ) 
    {
        while( have_posts )
        {
            the_post();
            ?>
            <div class="accordion-group">
                <div class="accordion-heading">
                    <h2><a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapse-<?php the_ID(); ?>">
                        <?php the_title(); ?>
                    </a></h2>
                </div>
                <div id="collapse-<?php the_ID(); ?>" class="accordion-body collapse in">
                    <div class="accordion-inner">
                        <?php
                        if ( is_singular()
                        {
                            the_content();
                        }
                        else
                        {
                            the_excerpt();
                        }
                        ?>
                    </div>
                </div>
            </div><!-- // .accordion-group -->
            <?php
        } // endwhile;
    } // endif;
    ?>
</div>
</div>

Leave a Comment