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

0

After the user completes a registration form, this form goes through all the validations, the data needs to be inserted into the wp_users table, the function below is playing 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 (user_cnpj) has been created in the table and it is necessary for the user-entered CNPJ to be registered in that field.

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

Note: The user_cnpj field currently exists in the table, but the record is being stored as NULL , because of wp_insert_user , the other fields are saving the fields correctly.

    
asked by anonymous 26.05.2017 / 20:09

2 answers

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 . The data will be saved in the wp_usermeta table:

update_user_meta( $user_id, $meta_key, $meta_value )
    
26.05.2017 / 22:39
2

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

Use the function quoted, update_user_meta .

Below is a complete example of how to add the field in the user edit screen and also how to save it. 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;
}
    
26.05.2017 / 22:51