LMS & eLearning

Snippet: Add a User to a LearnDash Group From a Form Submission

How to add a user to a LearnDash group programmatically from a form submission, with a reusable helper, Gravity Forms, WPForms and Contact Form 7 examples, an approval step, and testing notes.

Snippet: Add a User to a LearnDash Group From a Form Submission

An application form, a team sign-up page or an internal request form often ends with "put this person in the right group". LearnDash's group enrollment is a single function call, and every major form plugin has a hook that fires after a submission, so the integration is a few lines once you know which field holds the user and which group they should join.

The core function

ld_update_group_access( $user_id, $group_id ) adds a user to a group. It writes the user meta learndash_group_users_{group_id} and a group_{group_id}_access_from timestamp, fires ld_added_group_access with the user and group IDs, and returns true when it made a change. Passing true as a third argument removes the user instead and fires ld_removed_group_access. Group membership grants the group's courses on the fly, so no per-course enrollment is needed. Our guide to creating groups explains the data model.

A reusable helper

<?php
/**
 * Add a user to a LearnDash group by email, creating the account if needed.
 *
 * @param string $email    The user's email address.
 * @param int    $group_id The LearnDash group ID.
 * @return bool True if the user was added.
 */
function wwc_ld_add_email_to_group( $email, $group_id ) {
    $email    = sanitize_email( $email );
    $group_id = absint( $group_id );

    if ( ! is_email( $email ) || 'groups' !== get_post_type( $group_id ) ) {
        return false;
    }

    $user = get_user_by( 'email', $email );

    if ( ! $user ) {
        $user_id = wp_create_user( $email, wp_generate_password(), $email );
        if ( is_wp_error( $user_id ) ) {
            return false;
        }
        wp_new_user_notification( $user_id, null, 'user' );
    } else {
        $user_id = $user->ID;
    }

    return ld_update_group_access( $user_id, $group_id );
}

The helper validates the email and the group, finds or creates the user, sends the standard set-password email for new accounts, and enrolls. Keep the group check; passing a course ID by mistake would otherwise write meaningless meta.

Gravity Forms

add_action( 'gform_after_submission_5', 'wwc_ld_gf_add_to_group', 10, 2 );

function wwc_ld_gf_add_to_group( $entry, $form ) {
    $email    = rgar( $entry, '3' );   // Field ID of the email field.
    $group_id = absint( rgar( $entry, '7' ) ); // Field ID of a group selector, or hard-code.
    wwc_ld_add_email_to_group( $email, $group_id );
}

The number in the hook name is the form ID; rgar() reads a field by its ID. If the group is fixed, replace the second line with the ID.

WPForms

add_action( 'wpforms_process_complete_12', 'wwc_ld_wpf_add_to_group', 10, 4 );

function wwc_ld_wpf_add_to_group( $fields, $entry, $form_data, $entry_id ) {
    $email    = isset( $fields[2]['value'] ) ? $fields[2]['value'] : '';
    $group_id = 789;
    wwc_ld_add_email_to_group( $email, $group_id );
}

Again the number is the form ID and the array key is the field ID.

Contact Form 7

Contact Form 7 has no entry object; read the posted fields from the submission instance inside the wpcf7_mail_sent action and check the form ID so the callback only runs for the right form:

add_action( 'wpcf7_mail_sent', 'wwc_ld_cf7_add_to_group', 10, 1 );

function wwc_ld_cf7_add_to_group( $contact_form ) {
    if ( 42 !== (int) $contact_form->id() ) {
        return;
    }

    $submission = WPCF7_Submission::get_instance();
    if ( ! $submission ) {
        return;
    }

    $data  = $submission->get_posted_data();
    $email = isset( $data['your-email'] ) ? $data['your-email'] : '';

    wwc_ld_add_email_to_group( $email, 789 );
}

The field names are the tag names in the form editor. Because this hook fires only after the notification email is sent, a mail failure means no enrollment; use wpcf7_before_send_mail if enrollment should not depend on mail delivery.

Choosing the group from the form

A dropdown whose option values are group IDs lets one form feed many groups, for example a department picker. Validate the submitted value against the groups you expect rather than trusting it, since a visitor can alter form values:

$allowed = array( 789, 790, 791 );
if ( ! in_array( $group_id, $allowed, true ) ) {
    return;
}

Adding an approval step

For an application form rather than a sign-up form, you often want a person to approve before access is granted. The simplest pattern records the request in user meta and lets the helper run later from an admin action:

// On submission: record the request instead of enrolling.
update_user_meta( $user_id, 'wwc_ld_pending_group', $group_id );

// On approval (a button in the user list, a WP-CLI command, or a scheduled review):
$group_id = absint( get_user_meta( $user_id, 'wwc_ld_pending_group', true ) );
if ( $group_id && ld_update_group_access( $user_id, $group_id ) ) {
    delete_user_meta( $user_id, 'wwc_ld_pending_group' );
}

A WP-CLI approval is enough for a low-volume form: wp user meta get 456 wwc_ld_pending_group to see the request and a short wp eval call to approve it. For a steady flow of applications, a custom column and row action on the Users screen is a small addition a developer can make.

Removing a user from a form too

The same pattern works in reverse for a leave request or an opt-out form. Pass true as the third argument to remove the membership, and the group's courses stop being accessible the next time access is checked, while the learner's progress in those courses is kept in case they return:

ld_update_group_access( $user_id, $group_id, true );

Removal fires ld_removed_group_access, which is the hook to use if a leader should be told or a seat count should be released elsewhere. Do not create the user in this path; if the email has no account there is nothing to remove, and the helper's account creation would be a surprising side effect of an opt-out. Write a second, smaller helper that looks the user up and returns false when there is no match, and keep the group allow-list check in front of it, since an opt-out form is just as open to tampering as a sign-up form.

Seats, leaders and notifications

The function does not check the group's seat limit; enforce it yourself with the product model's seats-available method if the group is capped. It does not notify the learner either. The Notifications add-on's enroll into group trigger fires on the enrollment it makes. To notify the group leader, hook ld_added_group_access and look up leaders with learndash_get_groups_administrators( $group_id ).

Caveats

  • Creating users from a public form invites spam accounts. Use the form plugin's anti-spam and consider approval before enrollment.
  • The helper uses the email as the username. Change that if your site shows usernames publicly.
  • Form hooks run during the submission request; keep the callback fast and avoid remote calls.
  • Group enrollment date is submission time, which group-level drip and expiry count from.

Testing the integration

  1. Submit the form on staging with an email that has no account. Confirm a user was created, the set-password email arrived, and the user's profile lists the group.
  2. Submit again with an existing user's email. Confirm no second account was created and the existing user is now in the group.
  3. Submit with a tampered group value, if the group comes from the form, and confirm the allow-list rejected it.
  4. Log in as the new user and open one of the group's courses; it should be accessible without any further enrollment.

If the user is created but not enrolled, the usual cause is a group ID that points at a course or a draft group; the helper's post type check returns false silently in that case, so log the return value while testing.

When to get help

Seat enforcement, approval workflows, payment before enrollment, and syncing group membership with an HR system are the usual extensions. Our LearnDash development and integration teams build these; a LearnDash developer can usually connect a form to groups with approval in a short engagement. See LearnDash services for the wider offer.

Frequently asked questions

Which function adds a user to a LearnDash group programmatically?

ld_update_group_access with the user ID and group ID. Pass true as the third argument to remove them.

Do I also need to enroll the user in the group's courses?

No. Group membership grants the group's courses automatically whenever access is checked.

Can the form create the WordPress account too?

Yes, as the helper shows with wp_create_user, or use the form plugin's user registration add-on and run the group enrollment on its hook instead.

Does this respect the group's seat limit?

No. Check seats before calling the function if the group is capped.

Add WorldWin Coder to your preferred sources

Add worldwincoder.com as a preferred source on Google, or open this article in your AI assistant to use it as a source.

· Developers and project managers

Articles written and reviewed by the developers and project managers at WorldWin Coder, who build and maintain websites, web applications and mobile apps on WordPress, Moodle, PHP, Laravel, CodeIgniter and Flutter.

Free consultation

Need help with LearnDash?

Tell us what you are working on. A developer who does this every week reads your message and replies within one business day with next steps and a free quote.

  • Free consultation and quote
  • NDA on request
  • You own the source code
  • Reply within one business day

Tell us about your project

Add budget and timeline optional, helps us quote faster

This form is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Keep reading

Have something to build, fix or move?

Tell us where you are. A developer reads every inquiry, and you get next steps and a free quote within one business day.