Log out Wordpress and redirect to different URL

2019-05-24 02:53发布

I have a sign out on my site to log out of Wordpress

When logged out I would like to redirect uses to a different URL.

I'm using this in the functions.php

    add_action(' wp_logout ',' auto_redirect_external_after_logout ');
    function auto_redirect_external_after_logout(){
      wp_redirect( ' http://redirect-url ' );
      exit();
    }

and this in the header

    <li class="signOut"><?php wp_logout(); ?></li>

When I run this I get a long list of errors in the page

    Warning: Cannot modify header information - headers already sent by

2条回答
神经病院院长
2楼-- · 2019-05-24 03:39
<li class="signOut"><?php wp_logout(); ?></li>

That is the offending code, you are calling the wp_logout function that will log the user out and to do that WordPress needs to send the info (headers) to the browser and hence the error.

So the final action code should look like

add_action( 'wp_logout', 'auto_redirect_external_after_logout');
function auto_redirect_external_after_logout(){
  wp_redirect( 'http://redirect-url' );
  exit();
}

and the logout link should be changed to

<li class="signOut"><a href="<?php echo wp_logout_url(); ?>" title="Logout">Logout</a></li>
查看更多
Rolldiameter
3楼-- · 2019-05-24 03:43

If you want to use that hook, you're going to need to use JavaScript, since headers have already been sent:

add_action(' wp_logout ',' auto_redirect_external_after_logout ');
function auto_redirect_external_after_logout(){
    echo '<script>window.location.href = "http://redirect-url"</script>';
    exit();
}

Alternatively, a more elegant way is to use the wp_logout_url() function in place of your current logout link, and scrap the hook all together. Usage:

<a href="<?php echo wp_logout_url( 'http://redirect-url' ); ?>" title="Logout">Logout</a>
查看更多
登录 后发表回答