0
votes

What I need to do is send a custom form in the same time that the user subscribes to my Wordpress site. I'm using the hook add_action "user_register", this is my code:

<?php

    add_action('user_register', 'my_function');

    function my_function($user_id) { 

    $user_info = get_userdata($user_id);
    $username = $user_info->user_login;
    $mail = $user_info->user_email; 

?>

    <form id="my-form" action="http://....." method="get">
      <input type="hidden" name="list" value="9">
      <input type="email" name="email" value="<?php echo $mail; ?>">
      <input type="hidden" name="campo1" value="campo1">
      <input type="hidden" name="username" value="<?php echo $username; ?>">
      <input type="submit" />
    </form>

    <script type="text/javascript">
        document.getElementById('my-form').submit();
    </script>

<?php } ?>

What am I doing wrong? The function is working, the hook too with a different function. For example I tryed something like that:

<?php 

    add_action('user_register', 'my_function');

    function my_function($user_id) { 

    $user_info = get_userdata($user_id);
    $username = $user_info->user_login;
    $mail = $user_info->user_email;

    update_option('mail_test', $mail); 

} ?>

Any ideas? Thanks in advance for your help.

1

1 Answers

0
votes

I wouldn't advise hooking into the user_registration action, what happens when a user registers from wp-admin or you create a user in the back end? Wordpress is going to try and send some random form data that wont exist and may cause you issues.

The way to do this is to programatically create a user once you have validated your form data. you can do it like this...

if( $_POST ) {

    //Do all your validation then if all is correct use the following
    $password = wp_generate_password( 12, false );
    $user_id = wp_create_user( $email, $password, $username );

    //Set the user information
    wp_update_user(
        array(
            'ID'                => $user_id,
            'nickname'          => $firstname . ' ' . $lastname,
            'display_name'      => $firstname . ' ' . $lastname,
            'first_name'        => $firstname,
            'last_name'         => $lastname
        )
    );

}

Replace all the variables for user email and name with whatever you'd like and don't forget that with this method, the user will not receive any confirmation automatically so you will either have to show them their login and password in the success message or send them an email using wp_mail.

Hope that helps

Regards

Dan