WordPress get or set active menu class

How to get active menu class in wordpress, I want to get it in one plugin to change menu style.

Just to clear, I do not want active menu element class.

Read More
<ul id="menu-scroll" class="nav-menu">
<li id="menu-item-1461" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1461"><a href="#home">Home</a></li>
<li id="menu-item-1462" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1462"><a href="#about">About</a></li>
<li id="menu-item-1463" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1463"><a href="#services">Services</a></li>
<li id="menu-item-1466" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1466"><a href="#team">Team</a></li>
<li id="menu-item-1468" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1468"><a href="#blog">Blog</a></li>
<li id="menu-item-1467" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1467"><a href="#contact">Contact</a></li>
</ul>

In this I want to get “nav-menu” or i want to set new class like

<ul id="menu-scroll" class="my-nav-menu">

But not using themes file, I want to work it for all theme which is active.

Thanks In Advance,
Ajay

Related posts

2 comments

  1. This is relatively easily done with a filter.

    function alter_menu_class_wpse_113022($args) {
      // var_dump($args); // debug
      $args['menu_class'] = 'my-nav-menu';
      return $args;
    }
    add_filter('wp_nav_menu_args','alter_menu_class_wpse_113022');
    

    That will make this line:

    <ul id="menu-scroll" class="nav-menu">
    

    Look like this one:

    <ul id="menu-scroll" class="my-nav-menu">
    

    But that could cause themes to break horribly. If a theme has used that class to apply styles to the menu, which would be a reasonable thing to do, you’ve just broken all of that styling. The effected menus will look terrible and may not even function. This is a very, very bad idea. Please don’t do it.

  2. This is the following safer way to add class to nav menu wrapper as it will not overwrite existing class.

    function append_new_menu_class($args) {
      $args['menu_class'] = $args['menu_class'].' my-nav-menu';
      return $args;
    }
    add_filter('wp_nav_menu_args','append_new_menu_class');
    

    The following code adds custom class to nav menu ul tag

    function add_menuclass( $ulclass ) {
      return preg_replace( '/<ul>/', '<ul class="custom-class">', $ulclass, 1 );
    }
    add_filter( 'wp_page_menu', 'add_menuclass' );
    

Comments are closed.