Halloween Sale 15% off Ends in See the plans
PHP

LearnDash: Encouraging Email When a Quiz Is Failed

Emails students who did not pass a LearnDash quiz with their score and a link to try again, so they do not give up.

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

Code

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

add_action( 'learndash_quiz_completed', function ( $quizdata, $user ) {
    if ( ! $user instanceof WP_User || ! empty( $quizdata['pass'] ) ) {
        return;
    }

    $quiz_id = isset( $quizdata['quiz'] ) ? ( is_object( $quizdata['quiz'] ) ? (int) $quizdata['quiz']->ID : (int) $quizdata['quiz'] ) : 0;

    if ( ! $quiz_id ) {
        return;
    }

    $key = 'wpide_ld_fail_' . $user->ID . '_' . $quiz_id;

    if ( get_transient( $key ) ) {
        return;
    }

    set_transient( $key, 1, DAY_IN_SECONDS );

    wp_mail(
        $user->user_email,
        sprintf( 'Almost there: %s', get_the_title( $quiz_id ) ),
        sprintf(
            "Hi %s,\n\nYou scored %s%% on \"%s\". That is not a pass yet, but you can review the lessons and try again any time:\n%s\n\nYou've got this!",
            $user->first_name ? $user->first_name : $user->display_name,
            isset( $quizdata['percentage'] ) ? round( (float) $quizdata['percentage'] ) : 0,
            get_the_title( $quiz_id ),
            get_permalink( $quiz_id )
        )
    );
}, 10, 2 );

Notes

Sent at most once a day per quiz and student, so repeated attempts do not flood their inbox.

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.