Add an "active" class to the link according to the page accessed?

3

I'm setting up a theme for WordPress , and I need to add an active class in anchors , it works as follows:

I retrieve the URI from the current page and compare it to the text / value contained within the anchor that is automatically fetched by the WP itself's wp_list_pages( 'title_li=' ) function. If the condition returns true , it adds the active class, follows the complete 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');
    }
});
    
asked by anonymous 28.01.2016 / 18:48

2 answers

0

After several attempts I finally managed to make the links work. The big problem really was that I was not able to change the state of the uri variable, because the primitive types in JavaScript are immutable .

For this reason, the interpreter was replace from it (which was later replaced by split & join ), but discarded the change, and the variable returned to its initial state. Here's my solution below:

var sidebar = $( '.sidebar.manual' );
sidebar.find( '.sidebar.list li > a' ).each(function() {
    var uri = window.location.pathname.substring( 1 );

    // Armazena em uma variável o estado (já modificado) da variável "uri".
    var uriTreated = uri.split( '/' ).join( '' );

    // Trata o valor dentro de cada item da lista
    // referenciando-as como se fossem ID's.
    var linkValueTreated = $( this ).text().split( ' ' ).join( '-' ).toLowerCase();

    // Se estiver acessando a HOME (devido ao fato da URI retornar "/"
    // e a variável "uriTreated" tratar isso removendo a "/" por "")
    // adicione a variável "uriTreated" um valor referenciando
    // a ID da lista trazida pelo WordPress.
    if ( uriTreated == '' ) uriTreated = 'bem-vindo';

    // Se a URI for igual ao nome do item da lista
    // adicione uma classe "active" no link que é
    // referenciado por $( this )
    if ( uriTreated == linkValueTreated ) {
        $( this ).attr( 'class', 'active' );
    }
});
    
29.01.2016 / 20:48
3

WordPress already does this. It adds the .current_menu_item class to the option that matches the current page. So just use something like this:

add_filter('nav_menu_css_class' , 'my_special_nav_class' , 10 , 2);
function my_special_nav_class($classes, $item){
    if( in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}
    
28.01.2016 / 22:38