Simple dynamic JQuery Accordion with Advanced Custom Fields

Published

June 15, 2014

Category

Development

In this tutorial we are going to show you how to create a dynamic accordion using the WordPress Plugin “Advanced Custom Fields” and its Add-On “Flexible Content Field“. We are going to use the “Simple JQuery Accordion” of  CSS-Tricks as a base and adapt it to our needs. You find an example of a FAQ Page with this accordion here.

First you have to create a Flexible Content Field including at least two fields: One for the link and one for the content. You also can integrate more fields into the content area if you want to integrate more complex content.

ACF-Flexible-Content-Fields

Jquery

The original Jquery Script of CSS-Tricks displays all tabs closed in the initial state. We recommend to run the script at the bottom of the page to improve the loading time of your page.

(function($) {

var allPanels = $('.accordion > dd').hide();

$('.accordion > dt > a').click(function() {
allPanels.slideUp();
$(this).parent().next().slideDown();
return false;
});

})(jQuery);

 

We adapt the code that the initial state of the first tab will be open so it is more clear to the user how the accordion works.

(function($) {
var allPanels = $('.accordion > dd').hide();
$('.accordion > dt > a').click(function() {
allPanels.slideUp();
$(this).parent().next().slideDown();
return false;
});
$('.accordion > dt > a').eq(0).click()
})(jQuery);

PHP

We create our loop through the Flexible Content Field and include the <dt></dt> and <dd></dd> so they get duplicated. In the <dt>-tag we have to insert our title of a tab including an empty href-tag, inside the dt-tag we have to put all the content we want to display. Everything is inside the dl-tag what is the container of the whole accordion.

<div class="accordion">
<?php

// check if the flexible content field has rows of data
if( have_rows('ik_faq') ):

// loop through the rows of data
while ( have_rows('ik_faq') ) : the_row();

if( get_row_layout() == 'ik_question_answer' ):?>

<dt>
<a href=""><h3><?php the_sub_field('ik_question');?></h3></a>
</dt>

<dd>
<?php the_sub_field('ik_answer');?>
</dd>

<?php endif;

endwhile;

else :

// no layouts found

endif;

?>

CSS

As we do not need a lot of styling we just changed the padding of the H3 inside the dt-tag.

.accordion-container h3{
color: #ee1c31;
font-weight: 600;
padding-bottom: 5px;
}

This is how our Accordion can look like:
You can find the described JQuery Accordion here: http://www.austrianstartups.com/about-us/faq

JQuery-Accordion

More Information:
You can find the original article here: http://css-tricks.com/snippets/jquery/simple-jquery-accordion

INTERNETKULTUR | © 2018 | Imprint