LearnDash: Send Unenrolled Students to the Course Page
When a logged-in user opens a lesson or topic of a course they are not enrolled in, they are sent to the course page where they can enroll, instead of seeing a locked page.
Opens WPIDE on
Code
if ( ! defined( 'LEARNDASH_VERSION' ) ) {
return;
}
add_action( 'template_redirect', function () {
if ( ! is_user_logged_in() || ! is_singular( array( 'sfwd-lessons', 'sfwd-topic', 'sfwd-quiz' ) ) || current_user_can( 'edit_others_posts' ) ) {
return;
}
$course_id = (int) learndash_get_course_id( get_queried_object_id() );
if ( $course_id && ! sfwd_lms_has_access( $course_id, get_current_user_id() ) ) {
wp_safe_redirect( get_permalink( $course_id ) );
exit;
}
} );
Notes
Administrators and group leaders are never redirected.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.