I would like to create a redirect if the user is not logged in and clicks a course/lesson

I would like to create a redirect if the user is not logged in and clicks a course/lesson, can you help?

  • Nastia
    • Support Rock Star

    Hello Alejandra ,

    Hope you’re doing well!

    Out of the box, this is not possible I’m afraid. This will require a lot of custom coding. I see our developers have not provided a similar snippet before, I’ve flagged them in this thread so they could provide some feedback.

    Please note, our developers’ response time is longer-than-normal compared to support staff response times.

    We appreciate your patience!

    Kind regards,
    Nastia

  • Alessandro
    • Staff

    Hello Alejandra.

    On behalf of SLS team, we developed a simple snippet for CoursePress.

    By using this snipper, any guest (not logged in user), will be redirected to CoursePress login page and upon login, the user will be redirected to the course page.

    The snippet is:

    
    add_action( 'template_redirect', 
        function(){
            if ( ! class_exists( 'CoursePress_Core' ) ) {
                return;
            }
            
            if( ! get_current_user_id() && is_singular( 'course' ) ){
    
                global $wp;
                
                $redirect = add_query_arg( array(
                    'redirect_to' => home_url( add_query_arg( array(), $wp->request ) ),
                    '_wpnonce' => wp_create_nonce( 'redirect_to' ),
                ), get_site_url( null, CoursePress_Core::get_setting( 'slugs/login', 'student-login' ) ) );
                
                if( $redirect ){
                    wp_redirect( $redirect );
                }
    
            }
        } 
    );
    

    Append this code to your theme’s functions.php and it will work. :blush:

    Let us know if this worked for you.

    Kind regards,
    Alex.

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.