Search code examples
wordpressformscontact-form-7user-registration

wordpress subscriber with contact form 7


Does anyone know if with contact form 7 it is possible to have a checkbox that when it is activated by the visitor, this visitor is registered as a wordpress user, as a subscriber?

After the comment of Howard E, the question changes to...

How can be used wpcf7_before_send_mail for register a new user with the data of the form?

something like this, but I don't know if it is completely correct...

add_action( 'wpcf7_before_send_mail', 'register_user' );

function register_user($cf7) {
    $form_id = $cf7->id();
    
    if ($form_id == 300 || $form_id == 301 || $form_id == 302) {
        $submission = WPCF7_Submission :: get_instance();
    }
    if ($submission) {
        if (empty($posted_data)) { return; }
        
        $accept = $posted_data['acceptance-register-yes']; //acceptance check to be registered
        if (empty($accept)) { return; }
        
        $email = $posted_data['your-email'];
        $name1 = $posted_data['your-name'];
        $name2 = $posted_data['your-last-name'];
        $name = ''; //here will go function to delete spaces and generate user name from $name1 + $name2
        $pass = ''; //here will go function to random password
        
        function create_user($n,$p,$e){
            if (!username_exists($n)  && !email_exists($e)) {
                $user_id = wp_create_user($n, $p, $e);
                $user = new WP_User($user_id);
                $user->set_role( 'subscriber' );
            }
        }
        create_user($name,$pass,$email);        
    }   
}

many thanks


Solution

  • You can create a user and hook into wpcf7_before_send_mail like this.

    function wp_create_custom_account(){
      
      // Get the WPCF7 Submission instance
      $submission = WPCF7_Submission::get_instance();
    
        if ($submission) {
            $posted_data = $submission->get_posted_data();
    
            // Get the posted variables
            $username = isset($posted_data['username'])?$posted_data['username']:'';
            $password = isset($posted_data['password'])?$posted_data['password']:'';
            $eml = isset($posted_data['eml'])?$posted_data['eml']:'';
            
            // This can be radio or checkbox. Adjust your code accordingly
            $radio = isset($posted_data['radio'][0])?$posted_data['radio'][0]:'';
    
            if ($radio) {
              $user = $username;
              $pass = $password;
              $email = eml;
              if ( !username_exists( $user )  && !email_exists( $email ) ) {
                $user_id = wp_create_user( $user, $pass, $email );
                $user = new WP_User( $user_id );
                $user->set_role( 'subscriber' );
              } 
            }
        } 
      
      
    }
    add_action('wpcf7_before_send_mail','wp_create_custom_account');