Last active
November 27, 2023 12:40
-
-
Save andrewlimaza/430a30eb59d357563e49572ef5d6623a to your computer and use it in GitHub Desktop.
Retroactively enroll members into LearnDash Courses that are restricted with PMPro.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Adding some notes to this code snippet:
init
hook instead.LIMIT 50
to100
or1000
depending on your server to increase the batch amounts.