WordPress archive widget: group by years

What I wanted to do was group my archive entries by year and only show the months if a year is clicked. So this is my code in sidebar.php:

$args = array(
    'type'            => 'monthly',
    'limit'           => '',
    'format'          => 'html', 
    'before'          => '',
    'after'           => '',
    'show_post_count' => false,
    'echo'            => 0
);
$res = wp_get_archives( $args ); 
$archi = explode( '</li>' , $res );
$links = array();
foreach( $archi as $link ) {
    $link = str_replace( array( '<li>' , "\n" , "\t" , "\s" ), '' , $link );
    if( '' != $link )
        $links[] = $link;
    else
        continue;
}
                
$y = 0; 
foreach($links as $k => $v){
    $match = array();
    preg_match("/title='(.*?)'/si", $v, $match);    
    $tmp = explode(" ", $match[1]);
    if($y != $tmp[1]){
        echo "<li><b><a href='#' onclick='$(\".li_".$tmp[1]."\").show();'>".$tmp[1]."</a></b></li>";
    }
    $y = $tmp[1];
    echo "<li style='margin-left:10px;display:none;' class='li_".$tmp[1]."'>".$v."</li>";
}

That’s it! All you have to do is include jQuery.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.