LearnDash: Student Count Shortcode for Course Pages
Adds a [wpide_ld_students] shortcode that shows social proof such as "1,240 students enrolled" on a course page, cached so it stays fast.
Opens WPIDE on
Code
if ( ! defined( 'LEARNDASH_VERSION' ) ) {
return;
}
add_shortcode( 'wpide_ld_students', function ( $atts ) {
$atts = shortcode_atts( array( 'course_id' => 0, 'min' => 0, 'text' => '%s students enrolled' ), $atts, 'wpide_ld_students' );
$course_id = $atts['course_id'] ? absint( $atts['course_id'] ) : (int) learndash_get_course_id( get_the_ID() );
if ( ! $course_id ) {
return '';
}
$key = 'wpide_ld_count_' . $course_id;
$count = get_transient( $key );
if ( false === $count ) {
$query = new WP_User_Query( array( 'fields' => 'ID', 'number' => 1, 'count_total' => true, 'meta_key' => 'course_' . $course_id . '_access_from', 'meta_compare' => 'EXISTS' ) );
$count = (int) $query->get_total();
set_transient( $key, $count, 12 * HOUR_IN_SECONDS );
}
if ( $count < (int) $atts['min'] ) {
return '';
}
return '<span class="wpide-ld-students">' . esc_html( sprintf( $atts['text'], number_format_i18n( $count ) ) ) . '</span>';
} );
Notes
Use course_id="123" outside a course and min="50" to hide the count until it is worth showing. Counts direct enrollments and refresh every 12 hours.
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.