• Hello all,

    I need to add class to the anchor element ( tag) in the output from wp_nav_menu. I have remove div container and ul wrapper from the wp_nav_menu and stripped away the tags. So, all that is left is tags from the wp_nav_menu output.

    I have added classes to tags using add_filter in functions.php but I have no idea how to add an extra class to tags when the menu item is active i.e., the page url and url in tag are same.

    Below are my code snippets of wp_nav_menu in header.php and functions.php:

    <?php
                            $args = array(
                                'theme_location' => 'header-menu',
                                'container' => '',
                                'echo' => false,
                                'items_wrap' => '%3$s'
                            );
                            echo strip_tags( wp_nav_menu( $args ), '<a>' );
                        ?>
    <?php
    
        function register_my_menu() {
            register_nav_menu('header-menu',__( 'Header Menu' ));
        }
    
        add_action( 'init', 'register_my_menu' );
    
        function add_anchorclass( $anchorclass ) {
            return preg_replace( '/<a /', '<a class="w-nav-link nav-link"', $anchorclass );
        }
    
        add_filter( 'wp_nav_menu', 'add_anchorclass' );
    ?>

    Currently, when I am at Home, here’s the tag output in html:

    <a class="w-nav-link nav-link" href="http://localhost/theming-wordpress/">Home</a>

    I need to add an extra class whenever the menu item say Home is active like this:

    <a class="w-nav-link nav-link w-current" href="http://localhost/theming-wordpress/">Home</a>

    Please tell me how can I do this?

    Thanks,

    Shyam Singh

  • The topic ‘How to add class in anchor element for current item?’ is closed to new replies.