Log out WordPress and redirect to different URL

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.

Read More

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

Related posts

Leave a Reply

2 comments

  1. <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>
    
  2. 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>