skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    With the help of Rochelle, I have come with a code that finally works. This is it:

    add_action( 'gform_after_submission', 'create', 10, 2 );
    function create( $entry, $form ) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $user_login = wp_slash( $entry[3] );
        $user_email = wp_slash( $entry[2] );
        $user_pass  = substr(str_shuffle($chars),0,12);
    
        $userdata = compact( 'user_login', 'user_email', 'user_pass' );
        return wp_insert_user( $userdata );
    }
    

    Thanks to everyone who left a comment on this post!


  2. 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;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search