As more and more past entries are migrated over to the WordPress site, the year/month drop down list for the archives will get longer and longer.
It’s much cooler to show a list of the years, then when a year is clicked, it slides open to show links to the months. Turns out this can be done with a jQuery accordion.
Modifying HTML Markup
The wp_get_archives()
function returns an unordered list in HTML with links to every year-month with an entry. This will have to be parsed and modified so that the years are added as headings.
The basic approach is to use a regular expression to get an array of all the years, then count how many times each year appears. These numbers will be used later to count the number of entries before a year heading should be added.
//get an array of all the years
//the generated html is in reverse chronological order
//this can be used to determine when to insert a year header
preg_match_all("|<li><a .*>.*([0-9]{4}).*</a></li>|", $html, $out, PREG_PATTERN_ORDER);
$html = "";
$year_counts = array();
//counts the number of months with archives for each year
foreach ( $out[1] as $entry ) {
if ( isset( $year_counts[ $entry ] ) ) { //increment count for the year
$year_counts[ $entry ] = $year_counts[ $entry ] + 1;
}
else {
$year_counts[ $entry ] = 1; //1st time this year is encountered
}
}
$years = array_keys( $year_counts );
$counts = array_values( $year_counts );
$i = 0;
$k = 0;
foreach ( $years as $year ) {
$html .= '<h3>' . $year . '</h3><ul>'; //create a heading for each year
for ( $j = 0; $j < $counts[ $i ]; $j++) { //create an entry for each month in the year
$html .= $out[ 0 ][ $k ];
$k++;
}
$i++;
$html .= '</ul>';
}
It is also necessary to wrap the entire thing in <div>
tags with an ID of ‘accordion’.
jQuery Javascript Code
jQuery(document).ready(function() {
jQuery("#accordion").accordion({
autoHeight: false,
collapsible: true
});
});
Save this bit of code as a js file.
Including the Scripts
Download the jQuery accordion script from the website. This script and the one written in the previous section must both be included into the WordPress environment. wp_enqueue_script()
should be used for this.
function enqueue_accordion_script() {
wp_register_script( 'enqueue-accordion-script', get_stylesheet_directory_uri() . '/scripts/jquery-ui-1.8.13.custom.min.js',
array( 'jquery' ) );
wp_enqueue_script( 'enqueue-accordion-script' );
}
add_action( 'init', 'enqueue_accordion_script' );
function add_jquery_accordion() {
wp_enqueue_script( 'add-jquery-accordion', get_stylesheet_directory_uri() . '/scripts/jquery-accordion-init.js',
array( 'jquery', 'enqueue-accordion-script' ) );
}
add_action( 'init', 'add_jquery_accordion' );
For a good tutorial on how to load scripts, see scribu’s site.
Styling
That’s all you need to get a working jQuery accordion! You can now target the elements with CSS to achieve the desired look.