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();