cat brain.log | less

Getting it down on `paper`

WordPress Collapsible Monthly Archives

The default monthly archives are pretty ugly (IMO), so I set out to make the archives collapsible by year, with the current year expanded. The code took about 5 minutes to write, and 5 more to look up the workings of wp_get_archives. The code is comprised of 3 parts.

PHP/HTML generation:

echo('<h2>'._e('Monthly:').'</h2>');
$args = array(
  'type'   => 'monthly',
  'format' => 'html',
  'echo'   => false
);
 
$curYear = null;
foreach( explode("\n",wp_get_archives($args)) as $item ) {
  $year = substr(strip_tags($item),-4);
  if( $curYear === null || $year !== $curYear ) {
    $css = '';
    if( $curYear !== null ) {
      echo("</ul>\n");
      $css = ' style="display:none"';
    }
    echo(
      '<span onclick="toggle_year('.$year.');">'.$year.
      "</span><br/>\n".'<ul id="year_'.$year.'"'.$css.">\n"
    );
  }
  echo(preg_replace('/>(\S+)\s+\d+</','>$1<',$item)."\n");
  $curYear = $year;
}
if( $curYear !== null ) {
  echo('</ul>');
}

JavaScript event handling:

<script type="text/javascript">
function toggle_year(year) {
  var el = document.getElementById('year_'+year);
  if(el) { el.style.display=(el.style.display=="none")?null:"none"; }
}
</script> 

CSS styling (to make the collapsed YEAR headers look good):

<style type="text/css">
span.yearly {  font-size: 110%; font-weight: bold; cursor: pointer; }
</style>
 

Comments

No comments so far.

(comments are closed)