Make WordPress Core

Opened 10 months ago

Closed 10 months ago

Last modified 10 months ago

#59212 closed enhancement (fixed)

Call `add_user_meta()` when adding metadata to a new user

Reported by: johnbillion's profile johnbillion Owned by: johnbillion's profile johnbillion
Milestone: 6.4 Priority: normal
Severity: normal Version:
Component: Users Keywords: has-patch
Focuses: performance Cc:

Description (last modified by johnbillion)

When a user is created via wp_insert_user(), several meta fields are added to the user (including nickname, first name, last name, and various preferences). These are all added using update_user_meta() instead of add_user_meta(). This means an unnecessary database query is performed for each meta field to first check whether a matching meta row exists.

By switching to add_user_meta(), 11 database queries are saved by default when inserting a user.


  • Provide list of before/after queries when inserting a user
  • Confirm whether test coverage is sufficient
  • Provide steps for testing
  • Investigate the same for posts, comments, and terms in follow up tickets

Change History (7)

This ticket was mentioned in PR #5093 on WordPress/wordpress-develop by @johnbillion.

10 months ago

  • Keywords has-patch added; needs-patch removed

This saves an unnecessary database query to look up an existing row that does not exist.

Trac ticket: TBD

#2 @johnbillion
10 months ago

  • Description modified (diff)

#3 @johnbillion
10 months ago

Testing steps:

  • Call wp_insert_user() with at least user_login and user_email provided.
  • Confirm that all default meta fields are correctly inserted (several have an empty value by default):
    • nickname
    • first_name
    • last_name
    • description
    • rich_editing
    • syntax_highlighting
    • comment_shortcuts
    • admin_color
    • use_ssl
    • show_admin_bar_front
    • locale
  • Repeat with a meta_input field included to include custom user meta fields

The test_wp_insert_user_with_meta() test covers this functionality and is sufficient for confirming that user meta data is saved when a user is created.

Database queries:

Before this change: 54
After this change: 43

As expected, this saves 11 database queries, one for each of the default meta values stored with every user.

#4 @johnbillion
10 months ago

  • Milestone changed from Future Release to 6.4

#5 @johnbillion
10 months ago

  • Owner set to johnbillion
  • Resolution set to fixed
  • Status changed from new to closed

In 56478:

Users: Call add_user_meta() instead of update_user_meta() when adding metadata to a new user.

This improves the performance of inserting users as it removes one unnecessary SELECT query for every row of metadata inserted.

Props swissspidy, spacedmonkey, johnbillion

Fixes #59212

#7 @lkraav
10 months ago

Lgtm! Did you discover any clarity on why this was implemented with update_user_meta() in the first place?

Note: See TracTickets for help on using tickets.