سؤال

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?

هل كانت مفيدة؟

المحلول 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');

نصائح أخرى

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]

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى wordpress.stackexchange
scroll top