Adding custom menu items or <li> tags before and after your wp_nav_menu in WordPress

Cats: wordpress

If you need to add arbitrary or custom <li> tags before/after your WordPress navigation menu, such as calling wp_nav_menu, you can use this little bit of code.

Edit functions.php and add the following:

add_filter('wp_nav_menu_items',do_wp_nav_menu_items);
function do_wp_nav_menu_items($menu, $args=array()) {
        if( file_exists( TEMPLATEPATH . '/nav-menu-before.php' ) ) {
                ob_start();
                @include TEMPLATEPATH . '/nav-menu-before.php';
                $nav_menu_before = ob_get_clean();
        }
        if( file_exists( TEMPLATEPATH . '/nav-menu-after.php' ) ) {
                ob_start();
                @include TEMPLATEPATH . '/nav-menu-after.php';
                $nav_menu_after = ob_get_clean();
        }
        return $nav_menu_before . $menu . $nav_menu_after;
}

Create new files in your template directory called nav-menu-before.php and nav-menu-after.php (depending on what you need) and start adding stuff to it.

For example, to the newly created file nav-menu-before.php add this:

<li class="menu-item"><a href="http://randomwebsite.com">So Random</a></li>