Add a WordPress Nonce to Log Out menu links to prevent ‘Do you really want to log out?’ message

How to add a Log Out link to your WordPress menus without encountering the ‘Do you really want to log out?’ message.


If you’re attempting to add a Log Out link to the navigation of your WordPress website, you may start by linking directly to:

/wp-login.php?action=logout

However, when you follow this link, you’ll be greeted with a message like the one below:

You are attempting to log out of [site]
Do you really want to log out?

This is because WordPress requires a nonce field on its Log Out links. WordPress nonces are single use security tokens generated on page load to protect certain URLs and protect forms from misuse. A genuine Log Out link generated by the wp_logout_url() helper function would look like the example below:

/wp-login.php?action=logout&_wpnonce=1a2b3c4d5e

So how can we add a valid Log Out link to our WordPress menus including the required nonce field? The simple code snippet below will help.

Firstly, add a new Custom Link to your navigation with the following URL:

/wp-login.php?action=logout

Now, copy and paste the code snippet below into your functions file, or equivalent. Added to the wp_nav_menu_objects filter, this function will loop through your navigation items and, where the URL is equal to /wp-login.php?action=logout, will append a nonce field using wp_create_nonce(). The presence of this nonce field will prevent your visitors from seeing the ‘Are you sure?’ message when they follow your Log Out link.


/**
 *  Add nonce to logout URL in navigation
 */

function add_logout_url_nonce($items){
  foreach($items as $item){
    if( $item->url == '/wp-login.php?action=logout'){
         $item->url = $item->url . '?redirect_url=/&_wpnonce=' . wp_create_nonce( 'log-out' );
    }
  }
  return $items;

}

add_filter('wp_nav_menu_objects', 'add_logout_url_nonce');

A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones