Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.