Function to Enroll a User into a LearnDash Course
To enroll or unenroll a user from a LearnDash course programatically (using code), you use the ld_update_course_access() function.
Enroll
ld_update_course_access( $user_id, $course_id, $remove = false );
This function takes 3 arguments, the user id, course id, and whether you’d like to remove them from the course.
To get the course id, it’s helpful to use the learndash_get_course_id() function. This allows you to pass the ID of a lesson, topic, or quiz that belongs to the course, and then gives you the course id.
Here’s an example:
$user_id = 12;
$lesson_id = 321;
$course_id = learndash_get_course_id( $lesson_id );
// add user to course
ld_update_course_access( $user_id, $course_id, false );
Unenroll
To unenroll, you just add true for the last argument.
ld_update_course_access( $user_id, $course_id, true );
No Code Enrollment
To enroll or unenroll a user in a LearnDash course with no code, visit their user profile in the admin and scroll down to the enrollment section. Click the course name and use the arrows to change course access, then save.
Where do I have to place that code?
You should put that code in a hook inside a custom plugin.