Browse: Home / Snippets /

Redirect if user not authenticated or does not have access to course

Contents


Snippet #

/**
 * Learndash example of redirecting to different URL if the user
 * is not authenticated or does not have access to the course, lesson, topic etc.
 */
add_action( 'template_redirect', function() {	

	// Define the redirect URL here. 
	$REDIRECT_URL = home_url();
	
	// No other edits should be needed below this point. 
	////////////////////////////////////////////////////
	$ld_post_types = array( 'sfwd-courses', 'sfwd-lessons', 'sfwd-topic', 'sfwd-quizzes' );
	
	// Check if the loaded post is one of the valid LD post-type and the REDIRECT_URL is not empty.  
	if ( ( is_singular( $ld_post_types ) ) && ( !empty( $REDIRECT_URL ) ) ) {

		// If the user is not authenticated we send to the redirect URL. 
		if ( !is_user_logged_in() ) {
			wp_redirect( $REDIRECT_URL );
			exit();
		}

		// Get the course_id. This will take the lesson, topic etc and get the parent course_id
		$course_id = learndash_get_course_id( get_the_ID() );
		
		// Should always return some post id. But check just in case. 
		if ( !empty( $course_id ) ) {
						
			// If the user does not have access to the course_id then send to redirect URL
			if ( !sfwd_lms_has_access( $course_id, get_current_user_id() ) ) {
				wp_redirect( $REDIRECT_URL );
		        exit();
			}
		}
	}
}, 1);