getButterfly Logo getButterfly

WordPress Archives

WordPress can generate a yearly archive or a monthly archive. But not both. The code below uses a filter and a small jQuery code to create an expandable/collapsible archive list.

Here’s the archive filter:

/*
 * Add filter to query archives by year
 */
function whiskey_getarchives_filter($where, $args) {
    if(isset($args['year'])) {
        $where .= ' AND YEAR(post_date) = ' . intval($args['year']);
    }

    return $where;
}

add_filter('getarchives_where', 'whiskey_getarchives_filter', 10, 2);

Here’s the archive display code:

<dl class="tree-accordion">
    <?php
    $currentyear = date("Y");
    $years = range($currentyear, 1950); // Set the starting year
    foreach($years as $year) { ?>
        <dt><a href=""><i class="fa fa-fw fa-plus-square-o" aria-hidden="true"></i> <?php echo $year; ?></a></dt>
        <?php
        $archive = wp_get_archives('echo=0&show_post_count=1&type=monthly&year=' . $year);
        $archive = explode('</li>', $archive);
        $links = array();

        foreach($archive as $link) {
            $link = str_replace(array('<li>', "\n", "\t", "\s"), '' , $link);
            if('' != $link)
                $links[] = $link;
            else
                continue;
        }

        $fliplinks = array_reverse($links);
        if(!empty($fliplinks)) {
            echo '<dd>';
                foreach($fliplinks as $link) {
                    echo '<span>' . $link . '</span>';
                }
            echo '</dd>';
        } else {
            echo '<dd class="tree-accordion-empty"></dd>';
        }
        ?>
    <?php } ?>
</dl>

Here’s the jQuery code:

jQuery(document).ready(function(){
    var allPanels = jQuery('.tree-accordion > dd').hide();

    jQuery('.tree-accordion > dt > a').click(function() {
        $target = jQuery(this).parent().next();

        if(!$target.hasClass('active')) {
            allPanels.removeClass('active').slideUp();
            $target.addClass('active').slideDown(100);
        }

        return false;
    });

    jQuery('.tree-accordion-empty').prev().hide();
});

And, finally, here’s the CSS code:

.tree-accordion {
    line-height: 1.5;
}
.tree-accordion dt, .tree-accordion dd {}
.tree-accordion dt a {
    display: block;
}
.tree-accordion .fa {
    color: #666666;
}
.tree-accordion dd a {}
.tree-accordion dd span {
    display: block;
}
.tree-accordion dd {
    margin: 0 0 0 20px;
}

Note that I’m using FontAwesome for the plus icon.


Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.



If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply