Question

Accordion only works for first post...

I know there are similar questions already posted, and after reading through all of them I can't seem to figure out why mine is not working.

I am enqueuing the script in functions.php like so:

function my_scripts_method() {
    if ( !is_admin() ) {
        wp_enqueue_script('jquery-ui-accordion');
        wp_enqueue_script(
            'custom-accordion',
        get_template_directory_uri() . '/js/accordion.js',
        array('jquery')
    );
    }
}
add_action('wp_enqueue_scripts', 'my_scripts_method');

The .js file is like so:

jQuery(document).ready(function($) {
    $( "#accordion" ).accordion({
        collapsible: true, 
                active: false
    });
});

The custom post type loop is like so:

<?php while ( have_posts() ) : the_post(); ?>

<div id="accordion"> 

    <h3><?php the_title(); ?></h3> 

    <div>
    <?php the_content(); ?>
    </div>

</div> <!--#accordion-->

<?php endwhile; ?>

The accordion only works for the first post...

Any ideas why?

URL in question: premierdev1 (dot) hcg (dot) bz/prm_faq/

Was it helpful?

Solution 2

Simple Fix:

Just placed the accordion div outside of the loop. Worked like a charm!

<div id="accordion"> 

        <?php while ( have_posts() ) : the_post(); ?>

                <h3><a href="#"><?php the_title(); ?></a></h3> 

                <div>
                    <p><?php the_content(); ?></p>
                </div>

        <?php endwhile; ?>

</div> <!--#accordion-->

OTHER TIPS

You would benefit from using a tool such as Firebug in Firefox.

By viewing your site with Firebug enabled, looking at the Console tab, I am able to see that the reason things are breaking is due to an error:

TypeError: $ is not a function

var icons = $( ".selector" ).accordion( "option", "icons" );

That code is in your script file here:

http://premierdev1.hcg.bz/wp-content/themes/premier-reverse/js/accordion.js?ver=3.8.1

And the problem is that you can't use the $ function for jQuery in WordPress, you have to use jQuery - unless you are in a document ready function structured like so:

jQuery(function($) {
    // Do stuff in here, can use $ if you like
});

So, to correct this, I suggest changing that file to look like so:

jQuery(document).ready(function($) {
    $( "#accordion" ).accordion({
        collapsible: true,
        active: false
    });
    /* Move the below lines into your document ready */
    // getter
    var icons = $( ".selector" ).accordion( "option", "icons" );
    // setter
    $( ".selector" ).accordion( "option", "icons", { "header": "ui-icon-plus", "activeHeader": "ui-icon-minus" } ); 

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top