Query to get all enrolled courses from Learndash in Wordpress

Viewed 2037

I have a learndash site in WordPress with many courses. I want to display all the enrolled courses in a unorderd list to the user. I have a list which shows me all the courses, but not the current enrolled courses.

mycourses => true in the arguments is not working. My code to get all the courses:

$args= array('post_type' => 'sfwd-courses',
'post_status' => 'publish',
'order' => 'ASC',
'orderby' => 'ID',
'mycourses' => 'true'
);
                        
$loop = new WP_Query( $args );
                        
while ( $loop->have_posts() ) : $loop->the_post();
    echo the_title();
endwhile;

I don't like using the default shortcodes..

I don't understand how I could make the relation to the enrolled part. I hope someone with Learndash expierence could help.

2 Answers

Ok this is a bit of a work around and I'm sure there is better way to do it, but I found solution to query all enrolled classes. Here is a function that creates a shortcode for this:

function enrolled_classes(){
    $user_id = get_current_user_id();
    $courses = learndash_user_get_enrolled_courses( $user_id, array(), true );
    $args = array(  
        'post_type' => array('sfwd-courses'),
        'post_status' => 'publish',
        'posts_per_page' => -1, 
        'orderby' => 'date', 
        'order' => 'asc', 
        'post__in'      =>  $courses,
    );
    $enrolled = new WP_Query( $args );
    if ( $enrolled->have_posts() ) {
        while ( $enrolled->have_posts() ) {
            $enrolled->the_post(); ?> 
            <?php get_template_part('templates/class-thumb-loop'); ?>   
        <?php }
    } else {
        // no posts found
        echo 'no posts found';
    }
    /* Restore original Post Data */
    wp_reset_postdata(); ?>
    <?php
}
add_shortcode('enrolled', 'enrolled_classes');

Checkout this function: https://developers.learndash.com/function/learndash_user_get_enrolled_courses/

Using this function above you can query the Post IDs of the classes the user is enrolled. Then it's just a common WP_Query and you can use the parameter 'post__in' which accepts an array of Posts.

And lastly the get_template_part() just brings a file with a single

  • item.

    Hope this helped

  • Related