LearnDash: Give a Role When a Quiz Is Passed
Adds a role to students when they pass a chosen LearnDash quiz, for example a "Certified" role that unlocks a members area.
Opens WPIDE on
Code
if ( ! defined( 'LEARNDASH_VERSION' ) ) {
return;
}
// Quiz ID => role to add.
$wpide_ld_quiz_roles = array(
123 => 'contributor',
);
add_action( 'learndash_quiz_completed', function ( $quizdata, $user ) use ( $wpide_ld_quiz_roles ) {
if ( ! $user instanceof WP_User || empty( $quizdata['pass'] ) ) {
return;
}
$quiz_id = is_object( $quizdata['quiz'] ?? null ) ? (int) $quizdata['quiz']->ID : (int) ( $quizdata['quiz'] ?? 0 );
$role = $wpide_ld_quiz_roles[ $quiz_id ] ?? '';
if ( $role && get_role( $role ) && ! in_array( $role, (array) $user->roles, true ) ) {
$user->add_role( $role );
}
}, 10, 2 );
Notes
The role is added alongside the student's current role. Make sure the role exists (for example with a role editor plugin).
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.