Do You Want to Learn Marketing or Coding? Do You Want to Learn Marketing or Coding?

Creating a Dynamic JQuery
Accordion for WordPress

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Setting up the backend

The goal of this tutorial is to create a fancy dynamic jquery accordion that you can access from your wordpress theme.  This is great for FAQ pages or any page with lots of content.

Step 1.  Download wpalchemy from http://www.farinspace.com/wpalchemy-metabox/#download

Wpalchemy will help us create our custom metabox quickly.  Once you have the latest files place the two wpalchemy files into your theme’s folder.

Next navigate to the theme’s folder. For this demo I will be using the twentyeleven theme as an example… We will start creating the metabox by first going to the theme’s functions.php

Here, at the end of the function.php we will need to add a few lines of code to initiate the wonderful code provided by wpalchemy. Here is what we need to add:

// include the class in your theme or plugin
include_once 'MetaBox.php';
include_once 'MediaAccess.php';

// include css to help style our custom meta boxes
if (is_admin()) { wp_enqueue_style('custom_meta_css',
get_bloginfo('stylesheet_directory') . '/metabox/meta.css'); }
$wpalchemy_media_access = new WPALchemy_MediaAccess();
$custom_metabox = new WPAlchemy_MetaBox(array
(
	'id' => '_custom_meta',
	'title' => 'Add Accordion',
	'template' => STYLESHEETPATH . '/metabox/accordion.php',
)
);

The first line two lines call the MetaBox.php and MediaAccess.php which are needed to run the metabox…  Next we will include the location of our css file. The css file will help use control the look of the metabox in the backend. Lastly we will create an array which will hold the information about our metabox. The three basic elements we need are ‘id’, ‘title’, and ‘template’.  ‘ID’ is the id used in the Mysql database to identify the metabox content.  For this example I used _custom_meta.  ‘Title’ is the title that will appear on the metabox in the wordpress backend.  I named it “Add Accordion” because it made sense to me.  Finally template tells the system where our to find our metabox code, which is accordion.php located in a file named metabox. I pointed it to a dicrectory named metabox and named the file accordion. Next we will need to create the metabox folder and a file named accordion.php.

In accordion.php we will start by adding the following code:

<div class="my_meta_control">
<p style="padding-top:10px; float:left;">
     <a href="#" class="docopy-slider' button">Add New Slide</a>
</p>
<a style="float:right; margin:10px 10px;"
     href="#" class="dodelete-slider' button">
     Remove All
</a>
</div>

First we create a div and give it a class of my_meta_control.  This will give us control over the look of the panel later on. I added some styles to the links and paragraphs, I did this just to save time.  Normally I would add these styles to the CSS file.  Secondly we add a paragraph and place inside of it a link.  In this tutorial we are trying to create a dynamic accordion.  When using wpalchemy if we give a link the class=”docopy-slider’ button” the system will allow us to add a new element of a loop we will be creating later on.  The first part of the class “docopy” tells it to create a new item.  The “-slider” is the name of the panel we want copied.  I personally thing  of an accordion element as a slide so I named it slider.

Then I created a link gave it a class=”dodelete-slider’ button”.  This class will remove ALL of the accordion slides we create.  “dodelete” tells wpalchemy to delete and while the “-slider” tells the system to delete the slides.

Next just before the </div> we will add the following:

<div style="Clear:both"></div>
    <?php while($mb->have_fields_and_multi('slider')): ?>
        <?php $mb->the_group_open(); ?>

      <?php $mb->the_group_close(); ?>
  <?php endwhile; ?>

This section first clears the floating items we have above.  Secondly we start the metabox loop. We do this through the lines<?php while($mb->have_fields_and_multi(‘slider’)):?>  You will notice that “slider” matches the “-slider” in the links we added above.  We then open and close the group with the flowing codes <?php $mb->the_group_open():?> and <?php $mb->the_group_close();?>.  This is the loop we want to repeat.   We will be placing all of the items that we want to repeat in this portion of the code.  Finally we end the php loop with <?php endwhile; ?>

The final code we will add to this accordion file will take place inbetween the “the_group_open” and “the_group_close”.  Here is that code:

          <?php $mb->the_field('header'); ?>
	  <label>Title</label>
	  <p>
             <input type="text" name="<?php $mb->the_name(); ?>"
             value="<?php $mb->the_value(); ?>"/>
           </p>

	  <?php $mb->the_field('content'); ?>
          <label>Content</label>
               <textarea style="min-height:400px" name="<?php $mb->the_name(); ?>">
               <?php $mb->the_value(); ?></textarea>

         <a href="#">Remove</a>
          <br/><br/>

The first line <?php $mb->the_field(‘header)’);?>  tells our metabox to create a field named header.  The second line is just for labeling purposes.  Next we add the an input <input type=”text” name=”<?php $mb->the_name();?>” value=”<?php $mb->the_value(); ?>”/>  This tells the input to give it the proper name and value.

The  second section is where we will place the slides content.  We do this by adding initiating this line <?php $mb->the_field(‘content)’);?>.  Next we label it and create a textarea instead of an input this time.  We use a textarea this time to give us more space to work with.  Finally we will add a link and name it Remove.  This link will let us remove an individual slide.  The final accordion.php should look something like this:

 <div>
<p style="padding-top:10px; float:left;"><a href="#">Add New Slide</a></p>
<a style="float:right; margin:10px 10px;" href="#">Remove All</a>
 <div style="Clear:both"></div>
<?php while($mb->have_fields_and_multi('slider')): ?>
<?php $mb->the_group_open(); ?>

    <?php $mb->the_field('header'); ?>
    <label>Title</label>
    <p><input type="text" name="<?php $mb->the_name(); ?>"
value="<?php $mb->the_value(); ?>"/></p>

     <label>Content</label>
    <?php $mb->the_field('content'); ?>
    <div><textarea style="min-height:400px"
name="<?php $mb->the_name(); ?>"><?php $mb->the_value(); ?></textarea></div>
        <a href="#">Remove</a>
        <br/><br/>

<?php $mb->the_group_close(); ?>
<?php endwhile; ?>
</div>

 Implementing on the frontend

Now that the backend programing is complete we can work on putting the stored information to proper accordion form on the wordpress front end.  To start off we edit our header.php file by adding the following lines in between the <head> </head>:

<link rel="stylesheet"
href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css"
type="text/css" media="all" />

<script type="text/javascript"
 src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js">
</script>
 <script>
    $(function() {
         $("#accordion").accordion({ header: "h3"});

    });
</script>

The first four lines call for demo jquery style sheets.  Here you can link to your own style sheets to control the look of your accordion.  Or go to http://jqueryui.com/themeroller/ to download some preselected themes.  To speed up the process I just be pulling the demo css file.   The next four lines are the necessary jquery files.  If we don’t link to these files then accordion will not work properly.  Next we create a javascript function through the use of this line $(function() {.  We then establish what we want our function to do which is $(“#accordion”).accordion({ header: “h3”});.  The $(“#accordion”) tells the system too look for an id element with the name accordion.  Later on we will be creating a div that has this id.  Next we tell the system to create a jquery accordion when it finds the id  by adding the code .accordion({ header: “h3”});  The header: “h3” tells the jquery accordion to treat anything with h3 tags as the title of an accordion slide. You can add many more options within the .accordion() but for this tutorial we are keeping everything basic.  If you would like to know more about the jquery accordion and how it works then please go to this page:  http://jqueryui.com/demos/accordion/

How that we have the header updated we can edit or content page. For the following steps you will need to go to whatever php file that displays to users the content of your page section.  For me, and those using  the WordPress twenty_eleven template, the content-page.php carries the code necessary to display the wordpress pages.  The file should look something like this…

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header>
        <h1><?php the_title(); ?></h1>
    </header><!-- .entry-header -->

    <div>
        <?php the_content(); ?>
        <?php wp_link_pages( array( 'before' => '<div><span>' . __(
'Pages:', 'twentyeleven' ) . '</span>', 'after' => '</div>' ) ); ?>
    </div><!-- .entry-content -->
    <footer>
        <?php edit_post_link( __( 'Edit', 'twentyeleven' ), '<span>', '</span>' );
 ?>
    </footer><!-- .entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->

On this php file we will be adding a few lines below the part that says <?php the_content; ?>.  First we will start off by telling the system server that we are using php code.  Next we will create a connection to our metabox established earlier by adding $custom_metabox;   You should note that $custom_metabox is the array we defined at the end of our functions.php earlier.

<?php global $custom_metabox; ?>

Next we will create an if statement which will check to see whether or not we have any accordion information stored for that page.  We don’t want to create an accordion if we don’t have any use for it. We do this through the code:

if ($custom_metabox->the_meta() != '') { }

After that we will add some lines in between the brackets { and } that we just created.  We will first open and close a div. The id of this div will be equal to “accordion”.  If you recall up above we created a javascript that said to look for an id named accordion that is why we have id=”accordion”.  We do that by adding these lines:

echo '<div id="accordion">'; echo "</div>";

Next  we will need to create a loop that will gather all information from our database and place it in the proper format.  Meaning if we have created two slides in the backend we want the code to run twice while pulling each slide’s different information.  The following lines should be placed after the echo ‘<div id=”accordion”>’; and before the echo “</div>”;

while($custom_metabox->have_fields('slider')) { }

In between the brackets just created we will call for the title/header and content created form the  backend.  The accordion requires us to create an <h3> element for the title and place the slide content within a <div>.  To call content placed from the backend we will be using the code $custom_metabox->the_value(‘valuetitleyouwanttocall’);

So in this instance we will be using   $custom_metabox->the_value(‘header’); and $custom_metabox->the_value(‘content’);  We will echo the proper elements around our values to make the system recognize the slide.  The code looks like this:

echo '<h3><a href="#">';
$custom_metabox->the_value('header');
echo' </a></h3><div>';
 $custom_metabox->the_value('content');
echo "</div>";

After all is said and done the content-page.php should look something like this:

<?php
/**
 * The template used for displaying page content in page.php
 *
 * @package WordPress
 * @subpackage Twenty_Eleven
 * @since Twenty Eleven 1.0
 */
?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header>
        <h1><?php the_title(); ?></h1>
    </header><!-- .entry-header -->

    <div>
        <?php the_content(); ?>
        <?php wp_link_pages( array( 'before' => '<div>
<span>' . __( 'Pages:', 'twentyeleven' ) . '</span>', 'after' => '</div>' ) ); ?>

<?php
global $custom_metabox;
if ($custom_metabox->the_meta() != '') {
echo '<div id="accordion">';
    while($custom_metabox->have_fields('slider'))
{
        echo '<h3><a href="#">';
        $custom_metabox->the_value('header');
        echo'</a></h3><div>';
        $custom_metabox->the_value('content');
        echo "</div>";

} echo "</div>"; } ?>  

   </div><!-- .entry-content -->
    <footer>
        <?php edit_post_link( __( 'Edit', 'twentyeleven' ), '<span>', '</span>' );
 ?>
    </footer><!-- .entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->

Now your accordion should be complete! Just add some slides to any page and test it out!

I Really Need

Reviewing nerdy stuff is expensive.

Consider clicking on this ad & buying that item you REALLY wanted from Amazon.

It helps a ton!

Leave Your Thoughts