Navigation Menus

Programmatically Add Menu Item

WordPress comes with a default menu system which gives full control to the admin user of the site to change or create as many menu items as you want.

To access the menu system in the admin area you just need to go to Appearance -> Menu. From this screen you will be able to see all the menus that currently exist on your WordPress site, you can select any of these menus and change the menu items to anything you want. You can even create new menus and add these to different theme locations.

You can add any links you want, WordPress has a list on the left side of the page, that will display all the pages that are created on your site. If you have custom post types you can make these posts appear in the menu list if the option show_in_nav_menus is set to true.

With all the control that the user has on the menu system you would think that you will never need to change the menu items in the code. But there are occasions when you need to programmatically add or change menu items in a given menu.

The main times you will need to do this is to add a login or logout buttons to the navigation, this will most likely be on the main site navigation. If the current user is logged in you want to add a log out button and if they're logged out then you need to add a login button.

To do this we use the wp_nav_menu_items filter which will run after WordPress has created the HTML to print the menu on the screen. This gives us access to all the items that will be used, this means that we can simply add a new menu item to the end of the list with the links that we need.

add_filter( 'wp_nav_menu_items', 'add_logout_link', 10, 2);

 * Add a login link to the members navigation
function add_logout_link( $items, $args )
    if($args->theme_location == 'site_navigation')
            $items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>';
        } else {
            $items .= '<li><a href="'. wp_login_url() .'">Log In</a></li>';

    return $items;
Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days