You can use wp_logout_url()
function for logout link. It will automatically add nonce to the url.
Try this code:
add_action('template_redirect', function() {
if (empty($_SERVER['REQUEST_URI'])) return;
$uri = $_SERVER['REQUEST_URI'];
if (preg_match('#^/log-out/?$#', $uri, $matches) === 1) {
$logout_url = str_replace('&', '&', wp_logout_url());
wp_safe_redirect($logout_url);
die;
}
});
If you do not want to use wp_logout_url()
, then try to create nonce with ‘log-out’ string as this wp_create_nonce('log-out')
Updated code:
add_action('template_redirect', function() {
if (empty($_SERVER['REQUEST_URI'])) return;
$uri = $_SERVER['REQUEST_URI'];
if (preg_match('#^/log-out/?$#', $uri, $matches) === 1) {
wp_redirect(home_url(
'/wp-login.php?action=logout&redirect_to=%2F&_wpnonce=".wp_create_nonce("log-out')
), 302);
exit;
}
});