I have a WordPress site with WooCommerce. I would like to add a Logout option to the Menu that logs out the user without asking for confirmation.
So I included a menu custom link with as URL: /my-account/customer-logout/?_wpnonce=3d7c353c19&redirect_to=http%3A%2F%2Fwww.example.com. However, the nonce changes every time, so it will still ask for confirmation to log out…
This post shares something about how to get rid of the confirmation request with php. But I’m not familiar with php. How should I use this in the URL field of the custom link? That is, how can I populate the custom url with the dynamic nonce?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Using wp_logout_url() is your best choice.
You will need to create a <a> tag and in the href attribute output wp_logout_url()
<a href="<?= wp_logout_url('/'); ?>" title="Logout">Logout</a>
I passed / as an argument because after the user will click the link he will be redirected back to the homepage, you can change it to what ever you want
EDIT
Using code snippets you could create a shortcode and then use it, almost, where ever you want.
add_shortcode('bt_custom_logout_link', 'bt_custom_logout_link');
function bt_custom_logout_link ($atts) {
$link = '<a href="' . wp_logout_url('/') . '" title="Logout">Logout</a>';
return $link;
}
This function will register a new shortcode named bt_custom_logout_link, to use it you need to type it like this [bt_custom_logout_link]
Method 2
I ended up solving it using the plugin Code Snippets and the following code snippet based on https://wordpress.stackexchange.com/a/67342:
function change_menu($items){
foreach($items as $item){
if( $item->title == "Log Out"){
$item->url = wp_logout_url('/');
}
}
return $items;
}
add_filter('wp_nav_menu_objects', 'change_menu');
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0