How to store record in new column within wp_users table? (Wordpress)

Asked

Viewed 214 times

0

After the user fills in a registration form, this form goes through all validations, the data needs to be entered in the table wp_users, The function below is doing that role in my THEME:

$user_id = wp_insert_user( apply_filters( 'noo_create_user_data', $new_user ) );

So far so good, but a new column was created (user_cnpj) in the table and it is necessary that the CNPJ informed by the user is registered in this field.

What would be the best way for me to store this data correctly?

Obs.: Currently the field user_cnpj exists in the table, but the record is being stored as NULL, because of the wp_insert_user, the other fields are guarding the fields correctly.

2 answers

2

As Ricardo quoted it, do not change the WP tables, in the future this could be a big problem.

Use the above function, update_user_meta.

Below is a complete example of how to add the field on the user’s edit screen and also how to save. The code is functional, if you want to test, add to your functions.php.

add_action( 'show_user_profile', 'add_field_cnpj_custom_profile' );
add_action( 'edit_user_profile', 'add_field_cnpj_custom_profile' );
function add_field_cnpj_custom_profile( $user ) {
?>
    <h3><?php _e("Dados extra", "blank"); ?></h3>
    <table class="form-table">
        <tr>
            <th>
                <label for="cnpj">
                    <?php _e("CNPJ"); ?>
                </label>
            </th>
            <td>
                <input type="text" name="cnpj" id="cnpj" class="regular-text" value="<?php echo esc_attr( get_the_author_meta( 'cnpj', $user->ID ) ); ?>" />
                <br />
                <span class="description"><?php _e("Digite seu CNPJ"); ?></span>
            </td>
        </tr>
    </table>
    <?php
}

add_action( 'personal_options_update', 'save_field_cnpj_custom_profile' );
add_action( 'edit_user_profile_update', 'save_field_cnpj_custom_profile' );
function save_field_cnpj_custom_profile( $user_id ) {
    $saved = false;
    if ( current_user_can( 'edit_user', $user_id ) ) {
        update_user_meta( $user_id, 'cnpj', $_POST['cnpj'] );
        $saved = true;
    }
    return true;
}

1


Do not create new columns in the original Wordpress tables, this is never a good idea.

If you need to store the CNPJ use add_user_meta or update_user_meta. Data will be saved in the table wp_usermeta:

update_user_meta( $user_id, $meta_key, $meta_value )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.