phpwordpressgravity-forms-plugin

How can I automatically create a Wordpress user when submitting a Gravity Form?


I am totally new to PHP. I am trying to automatically create a WordPress user when a form is submitted with a custom plugin using the following code:

add_action( 'gform_post_process', 'wp_create_user', 10, 3 );
function wp_create_user( $username, $random_password, $email ) {
    $user_login = wp_slash( $entry[1]);
    $user_email = wp_slash( $entry[2]);
    $user_pass = wp_generate_password( $length = 12, $include_standard_special_chars = false );
    $role = 'Cp Client';

    $userdata = compact( 'user_login', 'user_email', 'user_pass' );
    return wp_insert_user( $userdata );
}}

I have also tried with gform_after_submission and changing the function's name, but then my website breaks.

What Am I doing wrong? Is this even possible? Could someone offer me a code example, please?

Thanks in advance,

Paco


Solution

  • You can try something like the following. (You may want to add a first, last and display name as well.) There is some more info here: https://usersinsights.com/create-wordpress-users-programmatically/

    add_action( 'gform_after_submission_185', 'register_a_user', 10, 2 );//replace 185 with the your form id
    function register_a_user($entry, $form ){
           $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
           $user_id = wp_insert_user( array(
              'user_login' => rgar( $entry, '1' ),
              'user_pass' => substr(str_shuffle($chars),0,12),
              'user_email' => rgar( $entry, '3' ),
              'role' => 'cp-client'//check the slug name of the role
           ));
           return;
        }