Let's say you want to add a Log out link so your users can logically logout.
It sounds pretty basic and easy and you will naturally use the wp_logout_url() function to get the logout url if you're adding the logout code conditionally. Of course it makes sense to show it only if the user is logged in.
The function usually returns a link that looks like this.
/wp-login.php?action=logout
The thing is WordPress will ask the user to confirm if the user really wants to logout ?!? But Why?
You are attempting to log out of ... Do you really want to log out?

Solution
The code below will solve the logout problem. It will allow you to have a custom logout link e.g. /logout and will logout the user right away without the need for the user to confirm anything. That's the way it should be. It will also update the default logout url as well. So you're very welcome 🙂
<?php
/**
* Plugin Name: WPSandbox Tutorial: #1498 - Custom Logout URL
* Plugin URI: https://wpsandbox.net/post1498
* Description: This code allows you to create a custom logout URL (/logout) that will log out the user and redirect them to the home page without prompting the user.
* Author: Svetoslav Marinov (Slavi) | WPSandbox
* Author URI: https://wpsandbox.net
* Version: 1.0.0
* Text Domain: wpsandbox_1498
* Requires at least: 3.7
* Requires PHP: 5.6
*/
/**
* @link https://wpsandbox.net/
*/
add_action('wp_loaded', 'wpsandbox_custom_logout_trigger_logout', 120);
/**
* This method hooks early and if the request is for the logout, it logs out the user and redirects to the home page or to
* the page that's set in redirect_to.
* @return void
*/
function wpsandbox_custom_logout_trigger_logout() {
if (empty($_SERVER['REQUEST_URI'])) {
return;
}
if (strpos($_SERVER['REQUEST_URI'], '/logout') === false) {
return;
}
wp_logout(); // logout the user
if (!empty($_REQUEST['redirect_to'])) {
$redirect_url = esc_url_raw( $_GET['redirect_to'] );
} else {
$redirect_url = home_url();
}
wp_safe_redirect($redirect_url);
exit;
}
add_filter('logout_url', 'wpsandbox_custom_logout_update_url', 100, 2);
/**
*
* @param string $logout_url
* @param string $redir
* @return string
*/
function wpsandbox_custom_logout_update_url($logout_url, $redir_url) {
$logout_url = home_url('/logout');
if (!empty($redir_url)) {
$logout_url = add_query_arg('redirect_to', urlencode($redir_url), $logout_url);
}
return $logout_url;
}
It is highly recommend that you create a custom plugin for this. You can use our WordPress Plugin Generator code for this code OR you can also add the code to the functions.php file.
The performance impact would be the same regardless where you put the code.
Again, the quality of the plugin is important to maintain a nice site performance.
If you install this as a plugin it will continue working when you switch to another theme.
If you need any customizations or tweaks feel free to contact us.