# 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.

- Type: PHP
- Runs: Frontend cl
- Category: [Courses & Community](https://wpide.com/library/category/learning/)
- Tags: learndash, redirect, enrollment
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/learndash-redirect-unenrolled-to-course/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "LearnDash: Send Unenrolled Students to the Course Page" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
