0

I am having trouble inserting logged-in user data, using the 'user_register' hook. The following code inserts a row in the database, but only inserts the 'email' column.

function nuevoPostulante()
    {
        global $wpdb;
        $tablaPostulante = $wpdb->prefix . 'postulante';
        $current_user = wp_get_current_user();
        $wpdb->insert(
            $tablaPostulante,
            array(
                'dni' => $current_user->user_login,
                'nombre' => $current_user->display_name,
                'email' => 'test@insert.com',
            )
        );
    }

    add_action('user_register', 'nuevoPostulante');

Columns with values ​​taken from '$ current_user' are empy, the insert do not seem to take data from the array.

I think it's a scope problem, I still don't understand how to fix it. Somebody could help me? Thank you!

0

user_register action allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.

So you wish to insert record for user when user register you can modify your code like follows:

add_action( 'user_register', 'nuevoPostulante', 10, 1 );
function nuevoPostulante( $user_id ) {
    global $wpdb;
    $tablaPostulante = $wpdb->prefix . 'postulante';
    $current_user = get_user_by( 'ID', $user_id ); // You can use get_userdata( $user_id ) instead of get_user_by() both can be work perfectly suite your requirement.
    $wpdb->insert(
        $tablaPostulante,
        array(
            'dni' => $current_user->user_login,
            'nombre' => $current_user->display_name,
            'email' => 'test@insert.com',
        )
    );
}
0

It's probably beacause of the simple fact that when a user (can) register for a site, then no user is logged in (yet), hence the object returned from wp_get_current_user() is empty.

Try checking and using values from the $_POST array instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.