Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andrewlimaza/430a30eb59d357563e49572ef5d6623a to your computer and use it in GitHub Desktop.
Save andrewlimaza/430a30eb59d357563e49572ef5d6623a to your computer and use it in GitHub Desktop.
Retroactively enroll members into LearnDash Courses that are restricted with PMPro.
<?php
/**
* Retroactively enroll members into LearnDash courses via a cron job (or whenever you want to use this callback).
*
* Does batches of 50 members at a time that aren't enrolled and should be.
* Use a tool like WP Crontrol or manually set up a cron job for this callback to automatically run every couple of minutes or hours.
* Add this code to your custom plugin by visiting this guide - https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
function my_pmpro_courses_silent_enroll(){
global $wpdb;
// Learndash not active, bail.
if ( ! function_exists( 'ld_update_course_access' ) ) {
return;
}
// Get all the members with an active membership ID and not in the enrollment table.
$sql = "SELECT pmu.user_id, pmu.membership_id, p.ID as course_id
FROM {$wpdb->prefix}pmpro_memberships_users pmu
LEFT JOIN {$wpdb->prefix}learndash_user_activity ld ON pmu.user_id = ld.user_id
LEFT JOIN {$wpdb->prefix}pmpro_memberships_pages mp ON pmu.membership_id = mp.membership_id
LEFT JOIN {$wpdb->prefix}posts p ON mp.page_id = p.ID
WHERE p.post_type = 'sfwd-courses'
AND ld.user_id IS NULL
AND pmu.status = 'active'
GROUP BY pmu.membership_id
LIMIT 50";
$members_to_enroll = $wpdb->get_results( $sql );
if ( empty( $members_to_enroll ) || ! is_array( $members_to_enroll ) ) {
return;
}
// Loop through all members and make sure they aren't enrolled and enroll them.
foreach( $members_to_enroll as $member ) {
if ( ! ld_course_check_user_access( $member->course_id, $member->user_id ) ) {
ld_update_course_access( $member->user_id, $member->course_id );
}
}
}
@andrewlimaza
Copy link
Author

Adding some notes to this code snippet:

  • This won't add user's back to enrollment once they were enrolled. For example if an admin removes their enrolled status from a course won't enroll them back.
  • Add this code to run on page load by using the init hook instead.
  • Adjust the LIMIT 50 to 100 or 1000 depending on your server to increase the batch amounts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment