Have you ever needed to save user specific data in WordPress? Have you ever wondered how user specific settings work in multisite? Do you want settings to be global and shared across all sub sites? Or do you need to retrieve the user meta setting for the current site where the user meta setting can be different in all sub sites?
Luckily WordPress covers all these scenarios. Let’s start with
Global user meta
In user profile page we already have several WordPress core settings:
- Color Scheme
- First Name
- Last Name
If you update First Name, the value is changed for all sub sites. That makes perfect sense, your name remains the same in all sub sites. I call that global user setting.
How to set global custom user meta
Sometimes we want to add our own settings in the user profile page. Custom user meta can be for example occupation, expire date in membership sites, or checkbox for approving the user.
There are four functions for adding, updating, retrieving or deleting custom user meta:
In our example we add simple text where meta key is called
$user_id = 1; $meta_key = 'multisite_user_meta_setting'; $meta_value = 'Sample text'; add_user_meta( $user_id, $meta_key, $meta_value );
Setting is saved in database table called
wp_usermeta. Now we could update, get or delete meta value but that’s not focus in this tutorial. If we use the same code in multisite install everything stays the same. User meta value remains as global setting across all sub sites.
User meta in WordPress multisite
In previous chapter we used
*_user_meta() functions but there are also
These functions checks against a site-specific meta key first, but if it doesn’t find anything, it falls back to a user-wide meta key. It means that same user can have different meta values for the same setting in multisite. For example we can have membership site in multisite install and expire date can be different in all sub sites when using
How does user meta works in multisite
We can use the same example as before but instead of using
add_user_meta() we use
$user_id = 1; $option_name = 'multisite_user_meta_setting'; $new_value = 'Sample text'; update_user_option( $user_id, $option_name, $new_value );
update_user_option function prepend the WordPress table prefix to the option name automatically. This is what happens behind the scenes.
- Let’s say our table prefix is
- Main site of multisite (and in single installs) meta key looks like this:
- In sub site there is also blog ID in the prefix. Meta key in sub site (where ID is 7) looks like this:
Now you can retrieve different meta values automatically and WordPress takes care of prefixing:
// Get setting $setting = get_user_option( 'multisite_user_meta_setting', $user_id );
WordPress checks the prefix in sub site where blog ID is seven (7) in this order:
So it even works when you switch from
*_user_option() functions because WordPress automatically falls back for non prefixed meta key. How cool is that!
That’s it for today, cheers!