How to add custom logout link in navigation menu?

If you’re designing a website with WordPress and you need to add a custom Logout link or button in the navigation menu.

You can follow the steps below:

  1. Navigate to Appearance>Menus

  2. Create Menu and add a custom link with URL = “https://example.com/wp-login.php?action=logout

  3. Done!

If you want to show different menu items to different users, like you created an e-Learning website where you want to show different menu items to logged-in and logged-out users or different menu to tutor and student, then you can follow this tutorial:

But wait, when you add the link like above it will show you a confirmation message like below:

It happens because your log out URL is missing the unique session id which looks like this https://devabhishek.com/wp-login.php?action=logout&_wpnonce=3899c7708e

So, How to avoid the confirmation message, follow the steps below:

  1. Navigate to Appearance>Theme Editor>functions.php

  2. Paste the following code and replace https://devabhishek.com to your actual URL where you want to redirect the user after logout.

add_action('check_admin_referer', 'logout_without_confirm', 10, 2);
function logout_without_confirm($action, $result)
{
    /**
     * Allow logout without confirmation
     */
    if ($action == "log-out" && !isset($_GET['_wpnonce'])) {
        $redirect_to = isset($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : 'https://devabhishek.com';
        $location = str_replace('&', '&', wp_logout_url($redirect_to));
        header("Location: $location");
        die;
    }
}

You’re done.

If you’re too lazy to add these things, just install this plugin.

Thanks and regards,
Abhishek Verma :slight_smile:

4 Likes