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.
Opens WPIDE on
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
- 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.