So you want to have an accordion effect on your options page? Like this?
Demo of accordion effect – click here
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi arcu leo, imperdiet et auctor quis, suscipit vel turpis. Vivamus erat justo, sagittis a venenatis euismod, mollis at justo. Cras dapibus leo a ipsum lobortis et pulvinar dolor sagittis. Etiam nec imperdiet massa. Duis felis elit, rhoncus id ullamcorper ac, pellentesque eget diam. In hac habitasse platea dictumst. Nunc eros enim, porta non placerat eu, mollis sit amet mi. Etiam eu sollicitudin eros. Sed et ipsum odio. Mauris feugiat suscipit eros ac consequat. In in arcu venenatis dolor volutpat placerat. Vestibulum tempus nibh non elit commodo gravida. Curabitur volutpat tincidunt leo sit amet consectetur. Sed gravida dolor nec metus eleifend luctus. Nam non leo pharetra mi ultrices lacinia.
First, go to the WordPress codex where there’s this page about enqueueing scripts. This is just a fancy way of saying ‘fetching scripts in WordPress,’ which results in something like this within the <head></head> elements of an HTML document:
<script type=âtext/javascriptâ src=âhttp://www.alchemweb.co.uk/wp-includes/js/jquery/jquery.js?ver=1.8.3â></script>
At the bottom of the codex page is a whole list of scripts that are included in WordPress by default – including a link to ‘jQuery UI Accordion’. Click on that link and you get taken to http://jqueryui.com/accordion/
So – to backtrack for a moment – scripts that are included in WordPress by default AREN’T activated. There’s too many of them and they’d take ages to download and there’d probably be all sorts of conflicts as well, so we only activate the scripts that we need. We’re going to activate the accordion script.
Before we go any further if we want to activate ANY one of the pre-included scripts on the front-end (the website that the user sees) it’s pretty simple. We just need to include it / queue it, and we use the ‘name’ or ‘handle’ (on that codex page) that WordPress gives it to do that.
Like this:
<?php
function i_want_to_fetch_a_script () {
wp_enqueue_script( âjquery-ui-accordionâ ); // the name or ‘handle’ of the script bundled with WordPress – we found the name on the codex page
}
add_action( âwp_enqueue_scriptsâ, âi_want_to_fetch_a_scriptâ );
?>
And if we want to fetch one of our OWN scripts for the front-end it’s also pretty simple. We just add something like this to functions.php:
<?php
function i_want_to_fetch_a_script () {
wp_register_script( ‘my-script’, get_template_directory_uri() . ‘/javascript/my_whizzy_script.js’ );
wp_enqueue_script( ‘my-script’ );
}
add_action( ‘wp_enqueue_scripts’, ‘i_want_to_fetch_a_script’ );
?>
We registered a script, gave it a ‘name’ and then ‘queued’ it – this is the simple version, but it’s possible to change the order in which scripts are output in the head or footer of the page, but we won’t go into that.
One potential little ‘gotcha’
get_template_directory_uri() fetches the script from the parent theme’s directory
get_stylesheet_directory_uri() fetches the script from a child theme directory. If you’ve got your own custom script and the theme that you use is regularly being updated you’ll want a child theme, so you’ll want to store your script in that child theme and you’ll want to reference it using get_stylesheet_directory_uri()
Options Pages
However, if we want to either upload our own script or activate one of the pre-included scripts on a THEME OPTIONS PAGE ONLY it gets a bit more complicated. There’s a bunch of code again on that same codex page about how to do that, a little bit on this codex page http://codex.wordpress.org/Function_Reference/add_theme_page on how to create an options page, and Otto also has a good tutorial on creating an options page. But the basic principle of registering and enqueuing scripts and stylesheets still applies.
If you want the code I used in my Childishly Simple theme to create an options page and activate scripts with a couple of extra links thrown in for good measure you can see this example options page text file (scroll to the bottom for the good bit).
Let’s get onto the good stuff!
Back to the Jquery Accordion page. I’ve chosen to use ‘Collapse content’ (menu, right hand side) meaning that every header can be collapsed rather than one always being open and displaying content.
At the bottom of that JQuery Accordion page there’s a link to ‘View Source’. You’ll see something like this in the head section:
<script>
$(function() {
$( “#accordion” ).accordion({
collapsible: true
});
});
</script>
How do you get that into the head of your WordPress options page? Easy – you create a file called accordion.js (for example) and paste everything that’s between the script tags into it, upload accordion.js to your theme directory, enqueue it as described above in functions.php and then upload functions.php. The script tags are automatically added by WordPress.
So in functions.php we now have this:
<?php
function i_want_to_fetch_a_script () {
wp_enqueue_script( âjquery-ui-accordionâ ); // the name or âhandleâ of the script bundled with WordPress
wp_register_script(‘accordion-js’, get_template_directory_uri() . ‘/javascript/accordion.js’); // Register our snippet of customiisation
wp_enqueue_script(‘accordion-js’); // Queue our snippet of customisation
}
add_action( âwp_enqueue_scriptsâ, âi_want_to_fetch_a_scriptâ );
?>
However, there are a couple more ‘gotchas’.
First, WordPress uses JQuery in ‘no-conflict’ mode. I know very little about JQuery but I do know we have to change accordion.js like this:
jQuery(document).ready(function($){
$( “#accordion” ).accordion({
collapsible: true
});
});
The next ‘gotcha’ is that all the headers that we click on to cause the accordion effect have been given the ID ‘accordian’ #accordion
But IDs are only meant to be be used once on an HTML page, and we’re probably going to be using the accordion effect more than once – so we want to use a class instead.
So now that snippet becomes:
jQuery(document).ready(function($){
$( “.accordion” ).accordion({
collapsible: true
});
});
The markup on our HTML page needs to be in this format, as described in the JQuery accordion API:
<div class=”accordion”>
<h3>First header</h3>
<div>First content panel</div>
<h3>Second header</h3>
<div>Second content panel</div>
</div>
Next thing – we want all our content areas to be closed on loading the page. So (from the JQuery API page again) the snippet of script in accordion.js becomes:
jQuery(document).ready(function($){
$( “.accordion” ).accordion({
collapsible: true,
active: false // We added this
});
});
We’d also like to show some flashy icons as background images to the left of the header that we’re going to click on – maybe a ‘+’ sign, and a ‘-‘ sign that will change when the content area slides down and slides up.
Here we go:
jQuery(document).ready(function($){
$( “.accordion” ).accordion({
icons: icons,// And now we’ve added this
collapsible: true,
active: false,
});
});
How do we display the icons? Using the ‘Inspect element’ tool that ships with FireFox we can see that they’re background images in some spans, with the spans having the classes of: ui-accordion-header-icon ui-icon
Where are these background images? Go to http://jqueryui.com/download/ and choose what components you want to download. I chose everything – otherwise you might have to play around later until you get the look that you want. Choosing everything has the disadvantage of larger file sizes for users to download (mainly the css files) but you don’t have to mess around discarding the bits that you don’t want. Hunt through the folders in your download and eventually you’ll find one called ‘images’. When you try and open some of the ‘sprites’ (lots of small images jumbled together in one big image) in a graphics programme they’re just blobs of color – I’m sure I’ll find out what’s going on eventually, but for now just upload the whole damned lot and have done with it.
So the sprites/images are uploaded to a folder called images in your theme directory.
Now find the style sheet in your accordion download. Save it somewhere and rename it – I like to start all my stylesheets with the word ‘style’, so for me it becomes style-accordion.css and that gets uploaded into the theme directory beside the theme style.css. This style-accordion.css also has to be enqueued, so now in functions.php we have this:
<?php
function i_want_to_fetch_a_script () {
wp_enqueue_script( âjquery-ui-accordionâ ); // the name or âhandleâ of the script bundled with WordPress
wp_register_script(‘accordion-js’, get_template_directory_uri() . ‘/javascript/accordion.js’);
wp_enqueue_script(‘accordion-js’);
wp_register_style(‘my-copied-accordion-styles’, get_template_directory_uri() . ‘/style-accordion.css’); // Register the style sheet
wp_enqueue_style(‘my-copied-accordion-styles’); // Queue the stylesheet
}
add_action( âwp_enqueue_scriptsâ, âi_want_to_fetch_a_scriptâ );
?>
But this still isn’t enough. We want that ‘+’ and ‘-‘ sign, remember? Where are they in those ‘sprites’?
Go to http://jqueryui.com/themeroller/ and you’ll see lots of small images (‘framework icons’) that can be moused over. When they’re moused over the tooltip shows a name e.g. .ui-icon-plusthick
Actually, it’s a class – because this is the class for a ‘thick’ (wide) plus sign. It’s actually the class that some spans are given by JQuery. The span with a class of .ui-icon-plusthick is styled in the stylesheet that we uploaded earlier.
Last thing. How do we give our accordion the class of .ui-icon-plusthick ?
Back to our snippet of JQuery in accordion.js
That snippet now becomes:
jQuery(document).ready(function($){
$( “.accordion” ).accordion({
icons: icons,
collapsible: true,
active: false,
});
});
var icons = {
header: “ui-icon-plusthick”, // Here we go – a class for our ‘plus’ sign
activeHeader: “ui-icon-minusthick” // And when hovered over the class changes
};
Obviously, with the information given here it’s also possible to easily create your own icons.
Conclusion
So now we have the default WordPress JQuery script activated, our snippet of customisation accordion. js uploaded to the theme’s ‘javascript’ folder, our copied and pasted stylesheet style-accordion.css uploaded to the theme folder, and both accordion.js and style-accordion.css registered and queued by this in functions.php :
Functions.php
<?php
function i_want_to_fetch_a_script () {
wp_enqueue_script( âjquery-ui-accordionâ ); // the name or âhandleâ of the script bundled with WordPress
wp_register_script(âaccordion-jsâ, get_template_directory_uri() . â/javascript/accordion.jsâ); // Register our own little snippet of customisation
wp_enqueue_script(âaccordion-jsâ); // Queue that little snippet
wp_register_style(âmy-copied-accordion-stylesâ, get_template_directory_uri() . â/style-accordion.cssâ); // Register the styles that we copied and renamed
wp_enqueue_style(âmy-copied-accordion-stylesâ); // Queue the styles
}
add_action( âwp_enqueue_scriptsâ, âi_want_to_fetch_a_scriptâ );
?>
accordion.js in the javascript folder
jQuery(document).ready(function($){
$( â.accordionâ ).accordion({
icons: icons,
collapsible: true,
active: false,
});
});
var icons = {
header: âui-icon-plusthickâ,
activeHeader: âui-icon-minusthickâ
};
And in the images folder are all the images that we downloaded from http://jqueryui.com/download/
Done.
NOTE: if copying and pasting use this text file, where I’ve changed the single and double quotes (otherwise it won’t work).