MemberPress + LearnDash: Enroll Members in Courses
Gives MemberPress members access to the LearnDash courses tied to their membership when they pay, and removes it when the membership expires.
Opens WPIDE on
Code
if ( ! class_exists( 'MeprUser' ) || ! function_exists( 'ld_update_course_access' ) ) {
return;
}
// Membership ID => LearnDash course IDs.
$wpide_mepr_ld_courses = array(
123 => array( 1001, 1002 ),
);
add_action( 'mepr-event-transaction-completed', function ( $event ) use ( $wpide_mepr_ld_courses ) {
$txn = $event->get_data();
$user_id = (int) $txn->user_id;
$granted = array_map( 'intval', (array) get_user_meta( $user_id, 'wpide_mepr_ld_granted', true ) );
foreach ( $wpide_mepr_ld_courses[ (int) $txn->product_id ] ?? array() as $course_id ) {
if ( ! sfwd_lms_has_access( $course_id, $user_id ) ) {
ld_update_course_access( $user_id, (int) $course_id );
$granted[] = (int) $course_id;
}
}
update_user_meta( $user_id, 'wpide_mepr_ld_granted', array_values( array_unique( $granted ) ) );
} );
add_action( 'mepr-event-transaction-expired', function ( $event ) use ( $wpide_mepr_ld_courses ) {
$txn = $event->get_data();
$user_id = (int) $txn->user_id;
$member = new MeprUser( $user_id );
if ( $member->is_already_subscribed_to( (int) $txn->product_id ) ) {
return;
}
// Courses still covered by another active membership stay.
$keep = array();
foreach ( array_map( 'intval', (array) $member->active_product_subscriptions( 'ids' ) ) as $active ) {
$keep = array_merge( $keep, array_map( 'intval', $wpide_mepr_ld_courses[ $active ] ?? array() ) );
}
// Only access this snippet granted is removed, never courses bought separately.
$granted = array_map( 'intval', (array) get_user_meta( $user_id, 'wpide_mepr_ld_granted', true ) );
$remove = array_intersect( array_diff( array_map( 'intval', $wpide_mepr_ld_courses[ (int) $txn->product_id ] ?? array() ), $keep ), $granted );
foreach ( $remove as $course_id ) {
ld_update_course_access( $user_id, $course_id, true );
}
update_user_meta( $user_id, 'wpide_mepr_ld_granted', array_values( array_diff( $granted, $remove ) ) );
} );
Notes
Map membership IDs to course IDs. Only access granted by this snippet is removed, and only when no other active membership includes the course.
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.