WordPress re-direct if specific user is already logged in

I currently have two members areas set up within a site. If a user logs in, and then decides to browse around the general website, when they click on the ‘Members Area’ icon again I want that page to work out which user is logged in, and then re-direct them to the correct members area. If no user is logged in, it should display the log in form.

I currently have the following:

Read More
<?php 
if ( $session->logged_in ) {
    if ( $username == "user1" ) {
        wp_redirect ( home_url("/members-area-1") );
        exit; }
    } elseif ( $username == "user2" ) {
        wp_redirect ( home_url("/members-area-2") );
        exit; 
    } else {     
?>

Currently it doesnt re-direct, it just displays the login form regardless of which user I’m logged in as. Any suggestions on how to make this work correctly?

(Be gentle, I’m still fairly raw when it comes to wordpress and php dev)

Many thanks,

Related posts

Leave a Reply

1 comment

  1. You may try this

    if ( is_user_logged_in() )
    {
        global $current_user;
        if( $current_user->user_login == 'user1' )
        {
            wp_redirect( home_url("/members-area-1") );
        }
        elseif( $current_user->user_login == 'user2' )
        {
            wp_redirect( home_url("/members-area-2") );
        }
        else
        {
            // logged in but doesn't match
        }
    }
    

    See is user logged in() at codex.

    Update: To solve the header sent warning issue you can add following code in your functions.php file to enable output buffering

    add_action('init', 'buffer_start');
    add_action('wp_footer', 'buffer_end');
    
    function callback($buffer) { return $buffer; } // This is not necessury if you don't use callback argument in the ob_start function.
    function buffer_start() { ob_start("callback"); }
    function buffer_end() { ob_end_flush(); }