Search code examples
phpwordpressnavigationwidgetargs

Is it possible to pass a nav widget in the Wordpress (Sidebar) new $args?


I've spent some time searching, but I haven't really found anything concrete in regards to passing new $args to a navigation widget. I did stumble across this post. However, I think the answer is a little overkill for what I'm trying to achieve.

To sum up the linked post it basically goes on to show how you could accomplish what I need, but only if an entirely new widget is created.


Specifically, I'm looking to either merge or overwrite the following $args exclusively for a menu widget placed within a Wordpress sidebar;

wp_nav_menu( array $args = array(
   'menu'              => "header-quicklinks",
   'menu_id'           => "quicklinks",
   'theme_location'    => "sidebar-header"
) );

If possible I would like to pass the ID of the widget, in my case nav_menu-6; to the function and have the $args only apply to that menu specifically, this way I can touch up the code to target other menus should I have the requirement.

Currently tinkering with the following;

function widget_nav_args($args){
  $menu = $args['menu'];
  if($menu->term_id === "menu-quick-links") { // < Error: non-object.
     return array_merge( $args, array(
            'menu_class' => 'TESTING', // for testing.
            // More settings here ... 
     ) );
  }
  return $args;
}
add_filter('widget_nav_menu_args', 'widget_nav_args');

Solution

  • You are nearly there. The widget_nav_menu_args filter accepts more parameters than just the $args for the nav. You want to look at the widget arguments which is the 3rd paremeter. It would look something like this:

    function widget_nav_args( $nav_menu_args, $nav_menu, $args, $instance){ // <- notice extra params..
    
        if( $args['id'] === 'sidebarheader' ) { // < This is where we check if it's the right widget
          return array_merge( $nav_menu_args, array(
              'menu_class' => 'TESTING', // for testing.
              // More settings here ... 
         ) );
      }
    
      return $nav_menu_args;
    }
    
    add_filter('widget_nav_menu_args', 'widget_nav_args', 10, 4);
    

    Notice I had to explicitly say how many arguments to pass to my filter function. Be sure to read through the documentation in the WP Codex here.

    Hope that helps!