phpwordpresshttp-redirectwoocommercelogout

wc_logout_url without confirmation AND redirect to current page in Wordpress WooCommerce


I would like to redirect the user that is logging out to the same page.

For instance: user is on category page and is logging out. After logging out I would like to have that the user is still on that specific category page (or any page the user is on). Now it will redirect the user to the homepage.

This is the code I'm using:

function iconic_bypass_logout_confirmation() {
    global $wp;

    if ( isset( $wp->query_vars['customer-logout'] ) ) {
        wp_redirect( str_replace( '&', '&', wp_logout_url( wc_get_page_permalink( 'home' ) ) ) );
        exit;
        }
    }
    add_action( 'template_redirect', 'iconic_bypass_logout_confirmation' );

I tried to change line 5 with the code below but without result.

wp_redirect( str_replace( '&', '&', wp_logout_url( get_permalink() ) ) );


Solution

  • According to the docs on wp_logout_url(), you can specify the redirect url. In this case, you should update the Logout link itself. So if you had a logout link in the header.php file as an example, you could update the wp_logout_url() reference to include the current page url. So, anytime a user clicked the logout link, it would also have the current page as the redirect link.

    All you need is the current page url. Referencing this post you can see one method for getting the current page url. This combined with the wp_logout_url() function, and your HTML might look something like this,

    <?php global $wp; ?>
    <a href="<?php echo wp_logout_url( home_url( $wp->request ) ) ?>">Logout</a>
    

    Now, the user will always be redirected from the previous page. If you do not have control over the Logout link itself, your only options would be to handle the logout via AJAX, or track the previous url yourself, via a query variable, session, cookie, etc.