Change WordPress user roles and capabilities › Forums › How to or FAQ › User logout without confirmation? › Reply To: User logout without confirmation?
12/04/2021 at 06:13
#7525
Vladimir
Keymaster
Hi,
Such confirmation comes out from the check_admin_referer('log-out');
function call, which if it does not find the valid _wpnonce value at logout URL shows the mentioned page with logout confirmation request:
function wp_nonce_ays( $action ) {
if ( 'log-out' === $action ) {
$html = sprintf(
/* translators: %s: Site title. */
__( 'You are attempting to log out of %s' ),
get_bloginfo( 'name' )
);
$html .= '</p><p>';
$redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
$html .= sprintf(
/* translators: %s: Logout URL. */
__( 'Do you really want to <a href="%s">log out</a>?' ),
wp_logout_url( $redirect_to )
);
}
As a workaround you can use the code below, which just ignores the result of _wpnonce checking:
add_action( 'check_admin_referer', 'logout_without_confirm', 10, 2 );
function logout_without_confirm( $action, $result ) {
if ( $action!=='log-out' ) {
return;
}
if ( $result ) {
return;
}
// It's a copy of logout code from wp-login.php, from line #666, just after check_admin_referer( 'log-out' ); call
$user = wp_get_current_user();
wp_logout();
if (!empty($_REQUEST['redirect_to'])) {
$redirect_to = $_REQUEST['redirect_to'];
$requested_redirect_to = $redirect_to;
} else {
$redirect_to = add_query_arg(
array(
'loggedout' => 'true',
'wp_lang' => get_user_locale($user),
), wp_login_url()
);
$requested_redirect_to = '';
}
/**
* Filters the log out redirect URL.
*
* @since 4.2.0
*
* @param string $redirect_to The redirect destination URL.
* @param string $requested_redirect_to The requested redirect destination URL passed as a parameter.
* @param WP_User $user The WP_User object for the user that's logging out.
*/
$redirect_to = apply_filters('logout_redirect', $redirect_to, $requested_redirect_to, $user);
wp_safe_redirect($redirect_to);
exit;
}
I think it’s safe as there is nothing more safer than just logout currently logged in user without any other conditions.