WordPress menu login / logout link

This post is more than 9 years old.

The WordPress drag-and-drop menus make it easy to build a custom menu for your website, but adding a login/logout link requires a little PHP code. It’s very simple though, and easy to add to any theme.

The trick with login / logout links in menus is that when you’re not logged in, you want a login link, but when you are logged in, you want a logout link instead. Also, it’s nice to be returned to your original page after logging in or logging out. WordPress has a couple of handy functions for that (wp_login_url() and wp_logout_url() give you links that return you to your original page), but you can’t add those links directly to the drag-and-drop menus through the WordPress admin.

What you can do, however, is add a regular login link to the menu, and then switch it out at runtime. You just need to add a custom link with a URL to your wp-login.php script (e.g. http://www.example.com/wp-login.php) and then add this little filter hook to your functions.php file in your theme.

add_filter('walker_nav_menu_start_el', 'menu_add_login_logout', 10, 2);

* filter menu items to replace login link with logout link when user logged in
* @param string $item_output
* @param WP_Post $item
* @return string
function menu_add_login_logout($item_output, $item) {
    if ($item->type == 'custom' && strpos($item->url, 'wp-login.php') !== false) {
        if (is_user_logged_in()) {
            // replace with logout link
            $item_output = sprintf('<a href="%s">Logout</a>', wp_logout_url(get_permalink()));
        else {
            // replace with login link returning to page/post
            $item_output = sprintf('<a href="%s">%s</a>', wp_login_url(get_permalink()), esc_html($item->title));

    return $item_output;

Job is done, or undone, depending on whether you’re already logged in.