I have a custom html form from which I am trying to insert records into a custom table .My problem is getting the current user name and inserting that value into the custom table. When the user clicks the Submit button the code below should fire. This is my php code:

require_once "wp-load.php";
require_once "dbconfig.php";
global $wpdb, $current_user;
$wpdb->insert( $table_name, array(
              'first_name' => $_POST['first_name'],
              'last_name'  => $_POST['last_name'],
               'email'     => $_POST['email'],
               'telephone' => $_POST['telephone'],
               'user_name' => [$current_user]

Any help is greatly appreciated. Been working on this for hours now, unable to find the solution.

Thanks in advance.


wp_get_current_user returns a WP_User object. You'll need to pull the name out of that in order to send it try $current_user->display_name in your insert statement. On that note, you should absolutely not be inserting unsanitized user entered data into your database. Please look into SQL injection and input sanitization.

  • Thank you for replying. I will definitely take care of sql injection. Just to update, to get the user name the following is the code: $current_user=wp_get_current_user(); $current_username = $current_user->user_login; – David D'Lima Mar 19 '19 at 8:12

The following is the code to insert user name into a custom table:

$current_username = $current_user->user_login;

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.