# LearnDash: Enroll Users When They Get a Role

> Gives users access to chosen LearnDash courses as soon as they are given a role, for example enrolling every new "Employee" in the compliance training.

- Type: PHP
- Runs: Run everywhere
- Category: [Courses & Community](https://wpide.com/library/category/learning/)
- Tags: learndash, roles, enrollment
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/learndash-enroll-by-role/

## Code

```php
if ( ! defined( 'LEARNDASH_VERSION' ) ) {
    return;
}

// Role => course IDs.
$wpide_ld_role_courses = array(
    'editor' => array( 123, 456 ),
);

$wpide_ld_enroll_role = function ( $user_id, $role ) use ( $wpide_ld_role_courses ) {
    foreach ( $wpide_ld_role_courses[ $role ] ?? array() as $course_id ) {
        if ( ! sfwd_lms_has_access( $course_id, $user_id ) ) {
            ld_update_course_access( $user_id, (int) $course_id );
        }
    }
};

add_action( 'set_user_role', function ( $user_id, $role ) use ( $wpide_ld_enroll_role ) {
    $wpide_ld_enroll_role( $user_id, $role );
}, 10, 2 );

add_action( 'add_user_role', function ( $user_id, $role ) use ( $wpide_ld_enroll_role ) {
    $wpide_ld_enroll_role( $user_id, $role );
}, 10, 2 );
```

## Notes

Access is added, never removed, when roles change. Works for role changes from the admin, other plugins and new registrations.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "LearnDash: Enroll Users When They Get a Role" 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/
