Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.