Paid Memberships Pro + LearnDash: Courses per Membership Level
Enrolls members in the LearnDash courses tied to their Paid Memberships Pro level and removes access when they cancel or their level expires.
Opens WPIDE on
Code
if ( ! function_exists( 'pmpro_hasMembershipLevel' ) || ! function_exists( 'ld_update_course_access' ) ) {
return;
}
// Level ID => LearnDash course IDs.
$wpide_pmpro_ld_courses = array(
1 => array( 1001 ),
2 => array( 1001, 1002, 1003 ),
);
add_action( 'pmpro_after_change_membership_level', function ( $level_id, $user_id ) use ( $wpide_pmpro_ld_courses ) {
$keep = array();
foreach ( $wpide_pmpro_ld_courses as $level => $courses ) {
if ( pmpro_hasMembershipLevel( $level, $user_id ) ) {
$keep = array_merge( $keep, array_map( 'intval', $courses ) );
}
}
// Only courses this snippet granted are ever removed, never ones bought separately.
$granted = array_map( 'intval', (array) get_user_meta( $user_id, 'wpide_pmpro_ld_granted', true ) );
foreach ( array_unique( $keep ) as $course_id ) {
if ( ! sfwd_lms_has_access( $course_id, $user_id ) ) {
ld_update_course_access( (int) $user_id, $course_id );
$granted[] = $course_id;
}
}
foreach ( array_diff( $granted, $keep ) as $course_id ) {
ld_update_course_access( (int) $user_id, $course_id, true );
}
update_user_meta( $user_id, 'wpide_pmpro_ld_granted', array_values( array_intersect( array_unique( $granted ), $keep ) ) );
}, 10, 2 );
Notes
Map level IDs to course IDs. Only access granted by this snippet is removed, so courses bought separately are never taken away.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.