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.
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.
1 2 3 4 5 6 7 8 9 10 11 |
(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.
1 2 3 4 5 6 7 8 9 |
(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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<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.
1 2 3 4 5 |
.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
More Information:
You can find the original article here: http://css-tricks.com/snippets/jquery/simple-jquery-accordion