LearnDash: Change Role After Course Completion
Adds a role (or replaces the current one) when a student completes a chosen course, such as promoting trainees to "Instructor".
Opens WPIDE on
Code
if ( ! defined( 'LEARNDASH_VERSION' ) ) {
return;
}
// Course ID => role.
$wpide_ld_course_roles = array(
123 => 'author',
);
$wpide_ld_replace_role = false;
add_action( 'learndash_course_completed', function ( $data ) use ( $wpide_ld_course_roles, $wpide_ld_replace_role ) {
$user = $data['user'] ?? null;
$course_id = isset( $data['course']->ID ) ? (int) $data['course']->ID : 0;
$role = $wpide_ld_course_roles[ $course_id ] ?? '';
if ( ! $user instanceof WP_User || ! $role || ! get_role( $role ) || user_can( $user, 'manage_options' ) ) {
return;
}
if ( $wpide_ld_replace_role ) {
$user->set_role( $role );
} elseif ( ! in_array( $role, (array) $user->roles, true ) ) {
$user->add_role( $role );
}
} );
Notes
Set $wpide_ld_replace_role to true to swap the role instead of adding it. Administrators are never changed.
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.