When we show the menu using wp_nav_menu, it creates menu with a structure like this:

<div class="container">
  <ul class="list">
    <li class="item">
      <a class="link" href="#">Link 1</a>
    <li class="item">
      <a class="link" href="#">Link 2</a>
    <li class="item">
      <a class="link" href="#">Link 3</a>
    <li class="item">
      <a class="link" href="#">Link 4</a>
    <li class="item">
      <a class="link" href="#">Link 5</a>

How can I change it to be like this:

<div class="container">
  <a href="#">Item 1</a>
  <a href="#">Item 2</a>
  <a href="#">Item 3</a>
  <a href="#">Item 4</a>
  <a href="#">Item 5</a>

I tried to customize it by filter, but I'm not able to check menu by arguments, the arguments just coming NULL.

My code is like this:

// page.php
wp_nav_menu([ 'theme_location' => 'sidebar_menu' ]);

// functions.php
function custom_menu($items, $args) {
    // ....
    print_r($args); // NULL

apply_filter('wp_nav_menu', 'custom_menu');
  • 1
    It's also possible to do this with a custom menu walker class, and may be possible using the options in the wp_nav_menu call
    – Tom J Nowell
    Sep 1 '19 at 22:41

Customizing menu markup can only be accomplished by adding a WordPress filter and using your own, custom menu template.

Unfortunately, menus are not a part of the WordPress template hierarchy so you need to do something like this:

add_filter( 'wp_nav_menu', function( $nav_menu, $args ) {
  if( 'my_custom_menu' == $args->menu->slug ) {
    // include a template with your required markup
    // reference both the $nav_menu and $args params in the template
    return include('my-nav-template.php');
  } else {
    return $nav_menu;
}, 10, 2);

This is a somewhat abbreviated answer. You'll need to read the WordPress documentation on the nav_menu object / function in order to know exactly how to parse the object but it's pretty straight forward.

Also, be sure that sidebar_menu is registered before calling wp_nav_menu() and that at least one menu has been assigned to the sidebar before trying this code.

Good luck!

  • Thank you so much! It might solve my problem
    – Lai32290
    Aug 30 '19 at 16:24
  • Feel free to write back with follow-up questions. I'll reply eventually :) Aug 30 '19 at 16:28
  • Additional questions should be started in their own thread.
    – Rob
    Aug 30 '19 at 18:10
  • Hey @TedStresen-Reuter, I'm not able to get anything from $args, it's coming NULL. I updated my question with sample code.
    – Lai32290
    Aug 30 '19 at 20:20
  • I tweaked my answer (fixed a variable name and the function call). Please re-read what I wrote and try again. I've verified this solution works (for me!) Aug 30 '19 at 22:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.