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.
Opens WPIDE on
Code
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 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.