Add Character Between Menu Items in WordPress using wp_nav_menu() Function

November 26th, 2014 - Posted by Steve Marks to PHP, Web Development.

Allowing navigation menus to be controlled from within WordPress makes amending the sites structure a simple task for the user. When setting up a menu you’d normally register it in your theme’s functions.php file then output it using the wp_nav_menu() function.

Most of the time this works fine and caters for the majority of scenarios. In the past however we’ve needed to go beyond this and add a character between the menu items. Something like this:


Now, you can pass certain arguments to the wp_nav_menu() function such as ‘before‘, ‘after‘, ‘link_before‘ and ‘link_after‘, but these just add HTML either side of the or link text respectively. What I needed was to have a separate list item (<li>) between each of the list items generated by the menu.

The Solution

The solution was relatively straightforward in the end and simply required amending the HTML that was generated by WordPress. The code we had originally was as follows:

wp_nav_menu( array( 'theme_location' => 'topNav' ) );

Once we’d updated this it turned out to look like so:

$nav = wp_nav_menu( array( 'theme_location' => 'topNav', 'echo' => false ) ); 

echo str_replace('</a></li>','</a></li><li class="separator"> // </li>', $nav);

In the above snippet of code we’re passing the ‘echo’ argument as false so it doesn’t get output straight to the screen and, instead, gets assigned a variable. Now that the HTML is in a string variable we can manipulate it. In this case we’re doing a string replacement to add a new list item that contains it’s own class and the slashes we require.

Of course you could use this for any character, not just slashes. You could use it to add pipe characters, dashes and so forth.

Tags: ,
This entry was posted on Wednesday, November 26th, 2014 at 10:29 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first