Add Active Class to Active WordPress Navigation Link
-
I’m developing a WordPress theme from scratch and I’m looking to add an active class to the navigation. I’ve found lots of articles for adding it to a WordPress menu that uses ul and li, but I’m using HTML5 nav and a for the navigation and can’t find how to add class=”active” to the active link.
The PHP code below is what I’m using to call the menu in the themes header.php file:
$headerNavigation = array ( 'menu' => 'navigation', 'container' => 'nav', 'echo' => false, 'items_wrap' => '%3$s', ); echo strip_tags(wp_nav_menu( $headerNavigation ), '<a><nav>' );I’m using the following code to register the navigation in the functions.php file:
function register_my_menus() { register_nav_menus( array( 'header-navigation' => __( 'Header Navigation' ) ) ); }
-
Hey,
If by active you mean the current page being viewed in the browser, then wp_nav_menu adds
.current-menu-item
This class is added to menu items that correspond to the currently rendered page.https://codex.wordpress.org/Function_Reference/wp_nav_menu#Current-Page_Menu_Items
Hope this helps 🙂
@wpfan1000
The .current-menu-item is only applied to navigation menus that use<li>. I was trying to build an HTML5 navigation using<nav>and<a>instead of<ul>and<li>. How can I get the .current-menu-item class applied to the<a>in my menu?This is what my menu output looks like:
<nav> <a href="/about">About</a> <a href="/contact">Contact</a> </nav>When I’m on /about I want .current-menu-item applied as a CSS class.
I see what you mean now.
Try this
https://codex.wordpress.org/Function_Reference/wp_get_nav_menu_itemsThis will allow you to generate any HTML you want.
You can add the “current class” by comparing the ID of the current page/post that the menu is being displayed on, with the id of each post that each menu item points to.
Eg if the current page has ID 5 and the menu item points to the page with ID 5, then you know that the menu item is current.
Here is an example of code for that:
https://stackoverflow.com/questions/10019493/adding-class-current-page-item
I hope (this time) this helps 🙂
The topic ‘Add Active Class to Active WordPress Navigation Link’ is closed to new replies.