Skip to main content
WPMU DEV Logo
  • Pro Plugins
  • Hosting
  • Domains
  • Site Management
  • Reseller
  • Plans & Pricing
    • WPMU DEV Membership

      All-in-one solution for WordPress management, optimization, updates and support.

    • Hosting

      Managed hosting with dedicated CPU, memory and IP address.

  • Free Hosting CreditsNEW
  • Log In
  • Sign up
WPMU DEV Logo

Products & Services

  • Pro Plugins
  • Hosting
  • Domains
  • Site Management
  • Expert Services
  • Reseller

Membership

  • Plans & Pricing
  • Log in

Hosting Promo

  • Free Hosting CreditsNEW
Sign up
Blog logo

The WPMU DEV Blog

Creating Custom Fields Manually in WordPress

Development

By Daniel Pataki 16 Apr 2016
4 comments

While there are some awesome plugins like CustomPress and Advanced Custom Fields that can help you create custom post type, if you really want to understand how they work you need to take a peek under the hood.

Design Tips for WordPress Developers

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
    • What is Post Metadata?
    • Custom Fields and Metaboxes
  • Manipulating Metadata
    • Getting Post Meta
    • Adding Post Meta
    • Updating Post Meta
  • Useful Tips
    • Underscored Meta Keys
    • Meta Fields Handle Arrays
    • All Metadata is Retrieved All The Time
    • Get All Metadata at Once

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.

Post meta in the database.
Post meta in the database.

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.

WordPress Custom Fields
WordPress Custom Fields

When you enter a name and a value you are directly creating rows in the postmeta table.

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.

Manipulating 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: get_post_meta(), add_post_meta() and update_post_meta().

Let’s begin by grabbing some data to use.

Getting Post Meta

The 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_1, 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:

Multiple meta items with the same key.
Multiple meta items with the same key.

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!

Loading gist 7a64927c41168bfb726870c86c450c70

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.

Loading gist e0fdb5a04a647a511e8371f49752fba8

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 add_post_meta().

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.

Loading gist 363b3b201b9d3527e20c1a9621de88a5

Useful Tips

That’s all there is to 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 update_post_meta() and 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

The 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.

Wrapping Up

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.

Share article

The perfect all-in-one
stack for WordPress

Find your plan Get started

Memberships start at just $3/m

DEV Logo

All the good WordPress stuff, once every two weeks

Subscribe

Related WPMU DEV Blog Posts

  • Creating Custom Content in WordPress: Taxonomies and Fields
  • Creating Custom Post Meta Boxes in WordPress
  • Creating Custom Database Tables for Your WordPress Plugins
  • You Asked, We Made It Happen! Add Client Profiles Directly to The Hub, No Billing Setup Required

User Gravatar Leave a comment

Create your free account to post your comment

Show password
Minimum 8 characters

or

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply

Already a member? Log in

Login to post your comment

Show password

or

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply

Register now | Reset password

Thanks for subscribing

DEV Logo

All the good WordPress stuff, once every two weeks. For example.

By clicking subscribe, you consent to receiving DEV from WPMU DEV.
(easy one-click unsubscribe, any time.)

4.9/5(2,994 reviews)
4.9/5(1,746 reviews)
5.0/5(592 reviews)
4.9/5(857 reviews)

Related products

MigrationFREE

Migrate unlimited sites to WPMU DEV

Learn more

Reseller

Easily start your own hosting company

Learn more

Expert Services

Professional help for tricky tasks.

Learn more

CampusPress

WordPress for educational institutions

CampusPress.com

Pro Plugins

Smush Pro Hummingbird Pro Forminator Pro Defender Pro SmartCrawl Pro Hustle Pro Branda Pro Snapshot Pro Shipper Pro Beehive Pro IVT Pro

Hosting

High Frequency Quantum Migration (Free) Email Hosting Pro Email Staging WAF Multisite Compare Hosting Hourly Backups

Domains

Pricing DNS Management

Site Management

Antibot Automation Configs Broken Link Checker CDN Analytics Uptime Monitor Backups Expert Services White Label Reports Performance Suite

Reseller

Templates Cloning Client Portal Clients & Billing Agency Partners Tickets

Resources

Translations Support Community Documentation DEV Blog

Company

About Us Careers Reviews Contact Roadmap System Status Product Security Premium Membership

Socials

LinkedIn Facebook Instagram X YouTube
SOC 2 Type II Certified
WPMU DEV LogoMade for web developers, by web developers
Terms Privacy An Incsub Project
© WPMU DEV 2025
Find out more about WPMU DEV

Join our weekly newsletter and get the tips and resources all the WordPress pros use - for free!

By clicking subscribe, you consent to receiving DEV from WPMU DEV.
(easy one-click unsubscribe, any time.)