Skip to content

Instantly share code, notes, and snippets.

@yitsushi
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save yitsushi/23a94f658b9f0e9493f0 to your computer and use it in GitHub Desktop.

Select an option

Save yitsushi/23a94f658b9f0e9493f0 to your computer and use it in GitHub Desktop.
Wordpress archive widget to annually grouped list
jQuery(function() {
var archive = jQuery('.widget_archive li a').toArray().map(function(item) {
var t = item.innerText.split(/ /);
return {
'link': item.getAttribute('href'),
'year': parseInt(t[1], 10),
'month': t[0],
'count': parseInt(item.parentNode.innerText.match(/\(([0-9]+)\)$/)[1], 10)
};
}).reduce(function(memo, item) {
if (!memo.hasOwnProperty(item.year)) { memo[item.year] = { items: [], count: 0 }; }
memo[item.year].count += item.count;
memo[item.year].items.push({ name: item.month, count: item.count, link: item.link });
return memo;
}, {});
var years = Object.keys(archive).reverse();
var root = document.createElement('ul');
for(var i = 0; i < years.length; i++) {
var yLi = document.createElement('li');
var yLink = document.createElement('a');
yLink.innerText = years[i] + " (" + archive[years[i]].count + ")";
var mUl = document.createElement('ul');
var mItems = archive[years[i]].items;
for (var j = 0; j < mItems.length; j++) {
var m = mItems[j];
var mLi = document.createElement('li');
var link = document.createElement('a');
link.setAttribute('href', m.link);
link.innerText = m.name + " (" + m.count + ")";
mLi.appendChild(link);
mUl.appendChild(mLi);
}
yLink.addEventListener('click', function() {
jQuery(this).next('ul').toggle()
});
jQuery(mUl).hide();
yLi.appendChild(yLink);
yLi.appendChild(mUl);
root.appendChild(yLi);
}
jQuery('.widget_archive ul').remove();
jQuery('.widget_archive').append(root);
jQuery('.widget_archive ul li:first ul').show();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment