Halloween Sale 15% off Ends in See the plans
PHP

LearnDash: Best Quiz Score Shortcode

Adds a [wpide_ld_best_score quiz_id="123"] shortcode that shows the student's best percentage on a quiz and whether they passed.

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

Code

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

add_shortcode( 'wpide_ld_best_score', function ( $atts ) {
    $atts    = shortcode_atts( array( 'quiz_id' => 0 ), $atts, 'wpide_ld_best_score' );
    $user_id = get_current_user_id();
    $quiz_id = $atts['quiz_id'] ? absint( $atts['quiz_id'] ) : ( 'sfwd-quiz' === get_post_type() ? get_the_ID() : 0 );

    if ( ! $user_id || ! $quiz_id ) {
        return '';
    }

    $best   = null;
    $passed = false;

    foreach ( (array) get_user_meta( $user_id, '_sfwd-quizzes', true ) as $attempt ) {
        if ( ! is_array( $attempt ) || (int) ( $attempt['quiz'] ?? 0 ) !== $quiz_id ) {
            continue;
        }

        $best   = max( (float) $best, (float) ( $attempt['percentage'] ?? 0 ) );
        $passed = $passed || ! empty( $attempt['pass'] );
    }

    if ( null === $best ) {
        return '<span class="wpide-ld-score">Not attempted yet</span>';
    }

    return '<span class="wpide-ld-score">' . esc_html( sprintf( 'Best score: %s%% (%s)', round( $best ), $passed ? 'passed' : 'not passed yet' ) ) . '</span>';
} );

Notes

Inside a quiz the quiz_id can be left out. Students who have not taken the quiz see "Not attempted yet".

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.