3
I’m putting together a theme for Wordpress, and need to add a class active in anchors, the operation is as follows:
I recover the URI of the current page and compare with the text/value contained within the anchor which is automatically brought by the function wp_list_pages( 'title_li=' )
of WP itself. If the condition return true, he adds the class active, follows the full code.
HTML:
<aside class="sidebar manual">
<ul class="sidebar list">
<?php wp_list_pages( 'title_li=' ); ?>
</ul>
</aside>
Javascript:
var uri = window.location.pathname.substring(1);
var sidebar = $('.sidebar.manual');
uri.replace('/', '');
sidebar.find('.sidebar.list li > a').each(function() {
var linkValueTreated = $(this).text().split(' ').join('-').toLowerCase();
if (uri == linkValueTreated || uri == '') {
if (uri == '') uri = linkValueTreated;
$(this).text(linkValueTreated).attr('class', 'active');
}
});