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

Asked

Viewed 340 times

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');
    }
});

2 answers

3

Wordpress already does this. It adds the class . current_menu_item in the option that corresponds to the current page. So you 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;
}

0


After several attempts I finally managed to make the links work. The big problem in reality was that I wasn’t able to change the state of the variable uri, due to the fact of the primitive types in Javascript were immutable.

For this reason, the interpreter did the replace (which was subsequently replaced by split & Join), however, I would discard the modification, and the variable would return to its initial state. Follow 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' );
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.