WordPress Batch Insert User Metadata

January 9th | By | Back to Blog

I’ve recently created a batch insert user metadata function on a WordPress project. The idea is just to create one MySQL insert instead of multiple add_user_meta because we want to keep the MySQL calls to the minimum. It does not handle validation (other than SQL injecting validations) because that is on the business logic part of the code.

function add_user_meta_batch($user_id, $metadata) {
	global $wpdb;
	$meta_values = array();
	foreach ($metadata as $key => $value) {
		$meta_values[] = $wpdb->prepare('(NULL, %s, %s, %s)', $user_id, $key, $value);
	$values = implode(', ', $meta_values);
	$wpdb->query("INSERT INTO $wpdb->usermeta (umeta_id, user_id, meta_key, meta_value) VALUES $values");

Hope this will be useful to anyone.

  • J.D. Grimes

    The only thing is, I don’t think doing it this way will update the cache. I’m not sure if that would cause problems or not.