Learndash change user role after completing the course

Question

I am moving a site from a LearnPress LMS to the LearnDash LMS, and I need to move over a custom function that changes the user role when the user completes the course (there is only one course right now). The user flow is the following: New user registers -> they are assigned a pre-subscriber role (this code is working, see below). Once the user completes the course, their user role changes from pre-subscriber to subscriber.

function cst_pre_creator_role() {
if ( get_option( 'pre_creator_role_version' ) < 1 ) {
    add_role( 'pre_subscriber', 'Pre Creator', array( 'read' => true, 'level_0' => true ) );
    update_option( 'pre_creator_role_version', 1 );
}}

add_action( 'user_register', 'cst_change_role', 10, 2 );
function cst_change_role($user_id, $userdata){
$user = new WP_User( $user_id );
    $user->set_role( 'pre_subscriber' );
}

The problem I am running into is how to link the Learndash function or functions to return the completion status as true or similar. I am looking at learndash_course_completed / learndash_course_status.

Below is the code that was working with LearnPress.

add_action('wp_head', function(){

    if(is_user_logged_in()){
            $user = wp_get_current_user();
            if ( in_array( 'pre_subscriber', (array) $user->roles ) ) {
                    $profile = LP_Profile::instance( $user->ID );
                    $Lpuser    = $profile->get_user();
                    $course_id      = 8217;
                    $course         = learn_press_get_course( $course_id );
                    $course_data    = $Lpuser->get_course_data( $course_id );
                    $course_results = $course_data->get_results( '' );
                    $status         = $course_results['status'];
                    $grade          = $course_data->get_graduation();
                    if($grade == "passed"){
                            // Remove role
                            $user->remove_role( 'pre_subscriber' );
                            // Add role
                            $user->add_role( 'subscriber' );
                    }
            }
    }
});

Any help with translating this LearnPress function into a LearnDash function would be greatly appreciated.

0
Alex Bertens 5 months 2022-03-30T20:34:01-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse