In this article, we explore WordPress user metadata, usually called simply WordPress user meta.
We’ll explain, among other things:
- How to add custom user meta fields in WordPress
- How to get user meta data in your WordPress PHP code
- How to delete and update user meta
- Our suggestions for easily building user metaboxes that are editable by other users.
What WordPress User Meta Is
WordPress user meta is “custom fields for your users.”
User meta has existed since WordPress 3.0, and it occupies an entire table of the WordPress database: wp_usermeta. So it’s a well-established piece of WordPress’s architecture. Now, what is it?
Here’s the simplest definition: User meta is “custom fields for your users”.
In other words, just as WordPress post meta—also called custom fields—lets you add any information you want to about your posts, WordPress user meta lets you add any information you want to about your users.
Now: Why would you want to add user meta?
Examples Where WordPress Custom User Meta Is Useful
Here are a few examples that come to mind—some from my own work with clients, and some from my use of third-party plugins. I’m sure you can think of others.
- I work with a WordPress site whose users are property managers. Each property manager has a Google Sheets spreadsheet of the properties he or she manages. The client asked me to save the URL of this spreadsheet for each user, for him or her to access in a private dashboard. I did this as a piece of user meta called “Spreadsheet URL.”
- I wrote a simple debate website in WordPress, where users participate in debates on randomized opposing teams. The site has a “leaderboard” that lists out the users who have won the most debates. I store each user’s win/loss record as a piece of custom user meta.
- We’ve used various membership plugins, such as MemberPress on courses.wpshout.com. Membership plugins use custom user meta to store elements of a user’s membership information.
- Yoast has a number of user meta fields that let you control the SEO side of that user’s author archive page. Below are the user meta fields for wpshout.com/author/fred.
You use user meta to “know more about your users” than the data they come with by default.
The common thread from this example is as follows: just like you use post meta to “know more about your posts” than the data they come with by default (such as their Yoast SEO title or whether they have a custom post author), you use user meta to “know more about your users” than the data they come with by default.
How to Add, Get, and Change WordPress User Meta Data
This section describes how to create, update, get, and delete WordPress user meta. Throughout this section, keep in mind the similarity of WordPress user meta to WordPress post meta: the two systems are almost identical, except that they work on different types of data objects (posts, made into objects as WP_Posts; users, made into objects as WP_Users). So if you understand our article on custom fields, this will be quick learning for you.
Adding or Changing WordPress User Meta Data: update_user_meta()
The function for either adding or updating WordPress user meta data is called update_user_meta(), and it looks as follows:
update_user_meta( $user_id, $meta_key, $meta_value, $prev_value );
Its arguments, in order, are:
- $user_id: The ID of the user to be affected.
- $meta_key: The name of the user meta field to be affected.
- $meta_value: The value that the user meta field should now take—this can be a string, integer, array, or any other data type depending on your needs.
- $prev_value: This optional parameter handles duplicate meta keys. You can almost always leave it out.
This function is almost identical to update_post_meta(), the equivalent function for changing post metadata, and the two functions work very similarly.
Code Example: update_user_meta()
Here’s a sample of the update_user_meta() function in action:
<?php function wpshout_you_found_this_post() { // If it’s not a logged-in user viewing this, never mind if( ! is_user_logged_in() ) : return; endif; // Set the “wpshout_found_this_page” user meta to true for the current user update_user_meta( get_current_user_id(), ‘wpshout_found_this_post’, true ); return ‘<p>You found this post!</p>’; } // Wrap the function in a shortcode to display anywhere add_shortcode( ‘wpshout_foundme’, ‘wpshout_you_found_this_post’ );
What does this code example do? If you were to install it as a plugin, and then put the shortcode [wpshout_foundme] on any post on your site, then whenever a logged-in user visited that post, that user’s value for the user meta key wpshout_found_this_post would be set to true. (The user would also see a paragraph that reads “You found this post!”)
You could use this for a weird Easter egg thing with your logged-in users, and then look at their user meta later to see how many of them had found the Easter egg. Or whatever. 🙂 Either way, it’s a working demo of update_user_meta().
Use update_user_meta(), or Change User Meta by Hand in the WordPress Admin Interface? It Depends
Just as with update_post_meta(), WordPress’s update_user_meta() function uses PHP to do something you can also do by hand: change a piece of post meta for a given user.
So do you change this information by hand, or using PHP? Once again, just as with post meta, it depends if you’re looking to make a few changes manually to specific users, or thousands of changes automatically.
Run a summer camp, storing campers as users, and want to let your camp counselors store each signed-up user’s allergy information as user meta? Use Pods (see below) to create an interface for them to enter that data.
Have thousands of users on a forum site, and want to automatically assign a “Veteran” badge to any user whose account is more than three years old? Do it with update_user_meta().
update_user_meta() vs. add_user_meta()
There’s a function, add_user_meta(), that is all about creating a piece of user meta if it doesn’t exist. Here’s the thing, though: update_user_meta() will do add_user_meta()‘s job for it if the piece of user meta you’re trying to update doesn’t already exist.
I’ve never found a real-world use for add_user_meta() (just like I haven’t for add_post_meta()), so I recommend ignoring it unless you’ve got a good reason to do otherwise.
Retrieving WordPress User Meta Data: get_user_meta()
The get_user_meta() function is quite simple and quite important: It’s how you retrieve a stored piece of user meta so you can do something with it. It looks as follows:
get_user_meta( $user_id, $meta_key, $single );
Its three arguments, in order, are:
- The ID of the user whose user meta you want to retrieve.
- A user meta key. In the example above, which we’ll continue here, the key we specified is wpshout_found_this_post. Note that this argument is technically optional: if you don’t fill it in, you’ll get an associative array of all the user’s meta data. (It’s rare that this is what I want, but it does happen occasionally.)
- Whether we’d like our custom field value as a single value or an array. If we set to true, as we did here, we get just the single value. If we don’t specify it, or set it to false, we’ll get back an array. If the data you’re expecting is just a single thing, like a string or an integer (so, most of the time), you’ll want to set this argument to true.
To make sure to note it, get_user_meta() is almost identical to its counterpart for posts, get_post_meta().
Code Example: get_user_meta()
Here’s a working code example:
<?php function wpshout_inflict_nag_message_to_find_the_post() { // If it’s not a logged-in user viewing this, never mind if( ! is_user_logged_in() ) : return; endif; // Get the “wpshout_found_this_page” user meta value for the current user // (as a single value, not an array) and save it to the variable $found $found = get_user_meta( get_current_user_id(), ‘wpshout_found_this_post’, true ); // Create a JavaScript nag message unless the value of $found is true if( ! isset( $found ) || $found !== true ) : // Don’t really insert JavaScript like this, by the way, it’s hacky echo ‘<script>alert( “You still need to find the post!” );</script>’; endif; } // Call the function write before the <head> section closes add_action( ‘wp_head’, ‘wpshout_inflict_nag_message_to_find_the_post’ );
What does the code above do? It pops up a super-annoying JavaScript alert on every page load until the user in question finds the Easter egg post from the update_user_meta() example above. Could be great for alienating all but your site’s most loyal users, should you want to do that for some reason.
Removing WordPress User Meta Data: delete_user_meta()
To remove a piece of user data from a user, use the function delete_user_meta(). This function is, again, almost identical in form and function to delete_post_meta()—except it’s for users, not posts—and it’s quite simple to use. It looks as follows:
delete_user_meta( $user_id, $meta_key, $meta_value );
Its arguments are:
- $post_id: The ID of the user to be affected.
- $meta_key: The name of the custom field to be deleted from the post’s metadata.
- $meta_value: This optional parameter handles duplicate meta keys. You can almost always leave it out.
Code Example: delete_user_meta()
Okay, let’s say we want to remove the wpshout_found_this_post flag from a user who did find the post—so that he or she can see more sweet, sweet JavaScript alerts.
<?php function wpshout_make_sure_user_is_haunted_by_nag_message() { // If it’s not a logged-in user viewing this, never mind if( ! is_user_logged_in() ) : return; endif; // Delete the “wpshout_found_this_page” user meta value for the current user delete_user_meta( get_current_user_id(), ‘wpshout_found_this_post’ ); } // Call the function at the beginning of WordPress’s loading process add_action( ‘init’, ‘wpshout_make_sure_user_is_haunted_by_nag_message’ );
Creating Metaboxes for User Meta: Use Pods
This part of the discussion is practical: What’s the best way to add user meta fields in WordPress?
The answer that I’ve come up with is simple: Pods. (That’s the name of a free plugin.)
The Pods plugin occupies the role for user meta that Advanced Custom Fields (ACF) plays for post meta. Of course, Pods can play ACF’s role for post meta too, if you like just using one thing.
Even Pods’s interface for adding user meta boxes looks extremely similar to ACF’s interface for adding post meta boxes:
What does Pods do? Just like ACF, Pods doesn’t add or create any actual meta values itself. In other words, Pods doesn’t change data in your wp_usermeta database table. What it does, instead, is create interfaces—metaboxes—for users to change that data themselves.
So just adding a user meta box called “Favorite Sport” doesn’t give any actual users a Favorite Sport, nor does it create a Favorite Sport “column” anywhere in one of your WordPress database tables. It’s only when someone starts to fill in sports for individual users that wp_usermeta starts to fill up with data—specifically, with the key-value pairs it uses to store information. Make sense?
Have You Meta User in Real Life?
You’ve just read a pretty hacky pun, and you also understand WordPress’s user meta system in general, including how to add user meta fields in WordPress, as well as how to get user meta data—both default and custom. Thanks for reading!
We’d love to hear from you in the comments below.
Content retrieved from: https://wpshout.com/how-to-create-and-use-wordpress-user-metadata-user-meta/.