In my previous post, “Breadcrumb with Structured Data for Blogger”, I mentioned that breadcrumbs are listed in alphabetical order, not showing the actual hierarchy.
If the labels are in a hierarchical (tree) structure, a label at the upper level is used more often than (or equal to) the labels at lower levels. So sorting labels by their frequency order, you can show the breadcrumbs in hierarchical order approximately (except when labels have the same frequency).
In this post, I change the breadcrumbs’ order from alphabetical to labels frequency by JavaScript.
Prerequisites
- Show the Labels gadget and check “Show number of posts per label” in “Configure Labels”.
- The label gadget
idmust beLabel1(normallyLabel1). - The breadcrumb list
idmust bebreadcrumb. - The breadcrumb list uses tags
<li>and its structured data format is RDFa.
FYI
These prerequisites are based on the following posts.
JavaScript
Insert the following JavaScript just before </body> in Edit HTML.
<script type='text/javascript'>
//<![CDATA[
(function(){
var label = document.getElementById('Label1');
if (label == null) return;
var breadcrumb = document.getElementById('breadcrumb');
if (breadcrumb == null) return;
// store label name and count into object
var labelCounts = {};
// 'div ul li' is for List, 'div>span' is for Cloud
var elms = label.querySelectorAll('div ul li, div>span');
[].forEach.call(elms, function(elm) {
if (elm.childElementCount == 2) {
labelCounts[elm.children[0].innerHTML] = Number(elm.children[1].innerHTML.replace(/[()]/g, ''));
}
});
// sort breadcrumbs by label frequency
var i = 0;
[].slice.call(breadcrumb.querySelectorAll('li'))
.sort(function (a, b) {
var a = a.textContent.replace(/\r?\n/g, '');
var b = b.textContent.replace(/\r?\n/g, '');
if (labelCounts[a] == null || labelCounts[b] == null) return 0;
if (labelCounts[a] > labelCounts[b]) return -1;
if (labelCounts[a] < labelCounts[b]) return 1;
}).forEach(function(li) {
// set content attribute for RDFa
pos = li.querySelector('[property="position"]');
if (pos != null) {
pos.setAttribute('content', ++i);
}
breadcrumb.appendChild(li);
});
})();
//]]>
</script>
Then, the breadcrumb list is displayed in label frequency order.
Note:
When the labels have the same frequency, the labels are sorted in alphabetical order (not changed).