Redirect user if not enrolled to course

[ad_1]

We don’t have a feature built-in for something like this, but if you wanted to have some courses publicly visible and some that are private, you may want to consider setting up a separate site for the private courses and enabling the Access Permissions settings for that site:

https://senseilms.com/documentation/settings/#access-permissions

Sorry I’m new to Sensei. I did some research and found the conditional block. I used this as a starting point for the following code snippet. I additionally included the option Self Enrollment not allowed in this example. You can place it in the functions.php of the child theme (either as a method or as a normal function). Maybe this will be helpful for others too.

/**
* Show 404 if user is not enrolled in the course and if self enrollment to the course is not allowed
*/

class Restricted_Course_Access {

/**
* Restricted_Course_Access constructor
*/

public function __construct() {
add_action( 'template_redirect', [ $this, 'restrict_access' ] );
}

public function restrict_access() {
$course_id = null;

if ( 'course' === get_post_type() ) {
$course_id = get_the_ID();
} elseif ( 'lesson' === get_post_type() ) {
$course_id = Sensei()->lesson->get_course_id( get_the_ID() );
}

// If no course ID is available, leave
if ( ! $course_id ) {
return;
}

// Check if the user is enrolled
$is_enrolled = Sensei()->course::is_user_enrolled( $course_id );

// If the user is not enrolled and the option Self Enrollment not allowed is selected, display 404 page
if ( ! $is_enrolled && get_post_meta( $course_id, '_sensei_self_enrollment_not_allowed', true ) == '1' ) {
global $wp_query;
$wp_query->set_404();
status_header(404);
nocache_headers();
include( get_query_template( '404' ) );
exit;
}
}
}

// Instantiate class to enable access control
new Restricted_Course_Access();

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer