0

I'm trying to redirect users when they visit my page template template-logout.php, but I keep getting the Wordpress "Do you really want to logout?" question despite wpnonce being generated. What am I doing wrong?

Here's an example of the type of URL being generated by my function below when I reach that WP confirmation page:

https://localssl:8890/wp-login.php?action=logout&redirect_to=https%3A%2F%2Flocalssl%3A8890&_wpnonce=752dc07192

CODE

template-logout.php

<?php 
/**
 * Template name: Log Out
 */

get_header(); 

// Logic handled via functions.php

get_footer(); ?>

functions.php

// Redirects for template pages
add_filter('template_redirect', 'osu_redirect_on_logout');
function osu_redirect_on_logout() {
    if ( is_page_template( 'templates/template-logout.php' ) ) {
        $logout_url = wp_logout_url( home_url() );
        wp_safe_redirect( $logout_url ); // Logout and Redirect to homepage
        exit;
    }
}

** EDIT **

Answer below by Gabriel is the better way of doing this, I was getting muddled with the redirection side of things. To make sure this method redirects to the homepage, this was my final code:

// Redirect to homepage when using wp_logout();
add_action( 'wp_logout', 'osu_redirect_homepage_after_logout');
function osu_redirect_homepage_after_logout(){
    wp_redirect( home_url() );
    exit();
}

// Redirects for template pages
add_filter('template_redirect', 'osu_redirect_on_logout');
function osu_redirect_on_logout() {
    if ( is_page_template( 'templates/template-logout.php' ) ) {
        wp_logout();
    }
}

1 Answer 1

1

If you are just trying to logout a user and redirect them back to the homepage, could you just use the wp_logout() function?

So instead of this:

if ( is_page_template( 'templates/template-logout.php' ) ) {
    $logout_url = wp_logout_url( home_url() );
    wp_safe_redirect( $logout_url ); // Logout and Redirect to homepage
    exit;
}

Your logic could just be:


if ( is_page_template( 'templates/template-logout.php' ) ) {
    wp_logout();
}
1
  • That's great, the only issue was the redirection to the homepage, but I added some code to make the default redirect for wp_logout() to the homepage via another function - I'll add it to the question above in case it's useful for others.
    – Osu
    Jan 3 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.