Visitor conditional redirect

Want to redirect visitor based on logged-in and not logged-in condition

  • Adam Czajczyk

    Hi Gibson

    I hope you're well today and thank you for your question!

    There are two "tweaks' to the code necessary:

    1. the login redirect and redirect for logged out users must be separated and hooked to different actions

    2. the redirect of all logged out users (visitors) to the "my-account" page must actually exclude the "my-account" page; if a user is already on "my-account" page no redirect should be performed - otherwise it will cause infinite redirect loop.

    Could you try this code please?

    // redirect to homepage on login
    function my_login_redirect() {
    
    		return home_url();
    
    }
    add_filter( 'login_redirect', 'my_login_redirect' );
    
    // redirect visitors (not logged in users) to my-account page
    function my_visitor_redirect() {
    
    	if  ( ( ! is_user_logged_in() ) && ( ! is_page( 'my-account') ) ) {
    		$redirect_to = home_url() . '/my-account/';
    		wp_redirect( $redirect_to );
    		exit;
    	}
    
    }
    add_action( 'template_redirect', 'my_visitor_redirect' );

    Give it a shot and let' me know, please, if it worked for you :slight_smile:

    Best regards,
    Adam

  • Gibson

    This issue has been solved with the help of Prathamesh Palve
    Below is the code that works

    }
    function my_login_redirect() {

    return home_url();

    }

    add_filter( 'woocommerce_login_redirect', 'my_login_redirect' );

    // redirect visitors (not logged in users) to my-account page
    function my_visitor_redirect() {

    if ( ( ! is_user_logged_in() ) && ( ! is_page( 'my-account') ) ) {
    $redirect_to = home_url() . '/my-account/';
    wp_redirect( $redirect_to );
    exit;
    }

    }
    add_action( 'template_redirect', 'my_visitor_redirect' );

    ……………………………….

    .hustle-modal-close .hustle-icon, .wpmudev-ui .hustle-modal-close .hustle-icon {
    width: 30px;
    height: 30px;
    cursor: pointer;
    display: none !important;
    margin: 0;
    padding: 9px;
    }

  • Adam Czajczyk

    Hi Gibson

    I'm glad to hear it's solved and thanks for letting us know.

    Let me just add an additional explanation, in case anyone else needed this code :slight_smile:

    The difference here is that my code was using core WP hook "login_redirect" while the one that solved the issue is using WooCommerce one "woocommerce_login_redirect". My code will work on a default setup but if there's WooCommerce involved (which I didn't take into account, sorry about that) then indeed the "woocommerce_login_redirect" must be used as WooCommerce overrides the native one.

    Once again, thanks for sharing solution!

    Have a great day,
    Adam

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.