Creating Custom Fields Manually in WordPress
Over the past 12 months, I’ve written a number of posts that focus on adding functionality to WordPress using custom fields. We’ve looked at creating custom post list templates, crafting the perfect travel blog and more.
While plugins like CustomPress and Advanced Custom Fields make creating custom post type easy-peasy, if you want to really understand how they work you need to take a look under the hood. So in this post, I’m going to show you how custom fields can be created manually.
Let’s get stuck in.
Exposing the CMS Aspect of WordPress
To me, custom field functionality is the basis of a CMS system. Custom posts and taxonomies are all great, but if you want to build something other then a blog-type system you need the ability to bind data to your posts.
The two primary ways to do this in WordPress are custom fields and custom meta boxes. Before we look into how these are used I think it is important to understand the underlying mechanism: post metadata.
What is Post Metadata?
Post metadata – or post meta – is a term that describes any sort of data that is attached to a post. Each single piece of data is stored in the
wp_postmeta table, which has four columns: ID, post_id, meta_key and meta_value.
The screenshot above is from phpMyAdmin, which shows the raw database data. The two rows shown are both attached to post_id 3974. The first row was added by WordPress to indicate who edited the post last. The second value is used by an SEO plugin to save the SEO title.
WordPress uses post meta internally for a number of things. You already saw how the last editor was saved. Another prominent example is saving a post’s featured image. When post 3974 receives a featured image a new post meta row is created with the meta key of
_thumbnail_id. The meta value contains the ID of the assigned image.
Custom Fields and Metaboxes
Both custom fields and meta boxes are user interface elements that allow you to input data into WordPress. The custom field section is provided by WordPress and hooks straight into the post meta functionality described above.
When you enter a name and a value you are directly creating rows in the
Metaboxes on the other hand are essentially UI helpers built into WordPress. They give you an easy way to add input mechanisms to post edit pages. You can choose to hook them up to the post meta functionality but you can use them for other things as well. We wrote about this recently in Creating Custom Post Meta Boxes in WordPress, so we’ll focus exclusively here on metadata.
A very user-friendly way to manipulate meta data is through the custom fields user interface in the admin. As developers, we need to use code to add data since our plugin or theme needs to be able to add/modify/remove this information.
Luckily, this is pretty simple. We only need three functions:
Let’s begin by grabbing some data to use.
Getting Post Meta
get_post_meta() function takes three parameters: the ID of the post, the key and whether we’re grabbing single or multiple values. The first two should be pretty clear but the third may be confusing.
Remember how a row of meta data contains a key and a value? There’s nothing to stop you from adding multiple rows with the same key. This may seem like bad practice at first but can actually be pretty useful.
Let’s say you’re creating a recipe blog and you want to store the ingredients as post meta. You could use
ingredient_2 and so on for meta keys but this quickly becomes tiresome.
What you should do instead is use
ingredient in each case. This would result in something like this in the database:
1.6 million WordPress Superheroes read and trust our blog. Join them and get daily posts delivered to your inbox - free!
If you would use
true as the third parameter of the
get_post_meta() function only one of these rows would be retrieved. If you use
false all rows will be returned as an array. Useful!
Adding Post Meta
To add post meta use the
add_post_meta() with three required parameters and one optional. The first parameter is the post ID, the second is the meta key, the third is the meta value.
The final – optional – parameter asks you to specify if this meta is unique or not. If you use false (or omit the parameter) the metadata will be added, even if one already exists with the same key. if set to true the data will not be added if a key with the same name already exists.
Updating Post Meta
Updating post meta is very similar to adding it. In fact, you can use the
update_post_meta() function to add data as well. If it doesn’t exist it will be created, just as if had used
The function takes three required and one optional parameter. The three required ones are post ID, meta key and meta value as usual. The fourth parameter defines how to handle situations where multiple values with the same meta key exist.
If you omit this parameter all rows with the same meta key will be updated with the new value. If you use the fourth parameter you can specify a previous value. This will only update rows that have a value that matches your specified one.
That’s all there is tom know about post meta! You can now save values and use them later on. Before you put all this knowledge to work let me finish up with four useful tips.
1. Underscored Meta Keys
I’m sure you noticed that in our very first screenshot from the database, the meta keys began with an underscore. This has special meaning in WordPress: it signifies metadata that should not be shown in the custom fields user interface.
Any metadata you add normally like we did with ingredients will actually show up. If you think the user shouldn’t be able to edit the data directly just prefix it with an underscore and it will be hidden from view.
2. Meta Fields Handle Arrays
Always try and use as few meta fields as possible. If your plugin provides 10 options don’t create a meta key for each. Use one meta key and save all your options as an array. You can pass arrays straight into the
add_user_meta() functions, WordPress will handle the rest.
In case you’re interested: WordPress serializes the data and saves it to the database. This results in a specially formatted string that is unserialized when it is retrieved from the database, returning to its array form.
3. All Metadata is Retrieved All The Time
To minimize overhead WordPress retrieves all meta data for a post if any single piece of meta data is requested. This means that you don’t have to worry about having 30
get_post_meta() function calls on a page. Only one database request will be made, everything is cached after that.
4. Get All Metadata at Once
get_post_meta() function can return all meta keys and values for the given post. Simply omit the second and third parameters, just pass the post ID and you’ll get a nice array of all data in the database for that post.
Custom fields and the metadata system makes WordPress the workhorse that it is today. Even better, this mechanism is extremely easy to use and can empower your plugins and themes to be so much more.
Practice using the functions in your work to get your head around the basics and you’ll be creating great applications from there in no time.
Do you use metadata in a unique way? Let us know in the comments below.