Skip to main content
WPMU DEV Logo
  • Products & Services
    Close Products and Services Submenu
    Everything WPMU DEV
    Personal

    Manage 1 Site, All 11 Pro plugins, services & much more

    Freelancer

    Manage 10 Sites, All 11 Pro plugins, services & much more

    Agency

    Manage Unlimited Sites, All 11 Pro plugins, services & much more

    Compare Plans
    Featured Plugins
    Smush Pro

    Optimize unlimited images

    Hummingbird Pro

    Build a faster website

    Defender Pro

    Keep your site safe from hackers

    Smartcrawl Pro

    Boost your website PageRank

    View all plugins
    Services & Add-ons
    The Hub

    Manage all your sites in one simple place

    The Hub Client

    Have your own client facing Hub

    Hosting

    Fastest, easiest, best-supported WP Hosting

    White Label our plugins

    Make our plugins, your plugins.

    White Label Reports

    Customize your client monthly reports

    Discover
    • Cloning
    • Email
    • Migration
    • Multisite
    • Automated Updates
    • Forms & Quizzes
    • Backups
    • Monitor
    • DNS
    • WAF
    • Security
    • Translations
    • CDN
    • Opt-ins & Popups
    • Documentation
    • Support
    • Roadmap
    • Partners
  • Plugins Plugins Submenu
    Close Plugins Submenu All Plugins
    Featured Plugins
    Smush Pro

    Image optimizer

    Hummingbird Pro

    Page Speed optimizer

    Defender Pro

    Security

    Smartcrawl Pro

    SEO optimization

    Snapshot Pro

    Schedule backups

    Forminator Pro

    Forms builder

    Hustle Pro

    Opt-ins & Popups

    Branda Pro

    White label WordPress

    Plugins
    WPMU DEV Dashboard

    Instant access to support and installation

    Shipper Pro

    Move WP websites with one-click

    Beehive Pro

    Customizable Google Analytics

    Integrated Video Tutorials

    Unbranded training videos

  • Hosting Hosting Submenu
    Close Hosting Submenu
    Hosting
    Hosting

    Fastest WP Hosting

    WAF

    First layer of defence

    DNS

    Simple Domain & DNS

    Email

    Offer email for clients

    Hosting Comparison

    Which is right for you?

    Cloning

    Duplicate your websites

    Migration

    Move your WP Sites

  • The Hub
  • Blog
Pricing
Log In
WPMU DEV Logo
Sign in
Products & Services
Everything WPMU DEV
Personal
Freelancer
Agency
Feature Plugins
Smush Pro
Hummingbird Pro
Defender Pro
Smarcrawl Pro
Services & Add-ons
The Hub Client
White Label our plugins
White Label reports
Discover
Cloning
Email
Migration
Multisite
Automated Updates
Forms & Quizzes
Backups
Monitor
DNS
WAF
Security
Translations
CDN
Opt-ins & Popups
Documentation
Support
Roadmap
Partners
Plugins
All Plugins
Smush Pro
Hummingbird Pro
Defender Pro
Smartcrawl Pro
Snapshot Pro
Forminator Pro
Hustle Pro
Branda Pro
WPMU DEV Dashboard
Shipper Pro
Beehive Pro
Integrated Video Tutorials
Hosting
Hosting
WAF
DNS
Email
Hosting Comparison
Cloning
Migration
The Hub
Blog
Pricing
Member Sign In
Close
Close

Sign In Sign up now

Show password
  • Blog
  • Development
  • Creating Custom Fields Manually...
WPMU DEV Logo Creating Custom Fields Manually in WordPress
Daniel Pataki Daniel Pataki   – April 15, 2016
2 Comments

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.

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 bc905e7fcb714f0a03c40941a82e1d5b

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 bc905e7fcb714f0a03c40941a82e1d5b

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 bc905e7fcb714f0a03c40941a82e1d5b

Useful Tips

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

 

Free Video Why 100 is NOT a Perfect Google PageSpeed Score (*5 Min Watch) Learn how to use Google PageSpeed Insights to set realistic goals, improve site speed, and why aiming for a perfect 100 is the WRONG goal.
Page speed imageWatch the video
Tags:
  • custom fields
  • metadata
Share this article
Daniel Pataki
Daniel Pataki Hello, I'm Daniel and I make things for the web. I'm the CTO at Kinsta and I write for a number of amazing publications like WPMU DEV and Smashing Magazine. In my spare time you'll find me playing board games or planning the next amazing office game like the not-at-all-destructive Megaball.
Do you use metadata in a unique way? Let us know in the comments below.

What is WPMU DEV?

Play btn
WPMU Video
Learn more

We Tested All The

Best WP Hosts!!!

View Results

Find us on

  • Link to WPMU DEV Facebook
  • Link to WPMU DEV Twitter
  • Link to WPMU DEV LinkedIn
  • Link to WPMU DEV Instagram

Related and Most Recent Posts

Creating Custom Content in WordPress: Taxonomies and Fields
Creating Custom Post Meta Boxes in WordPress
Creating Custom Database Tables for Your WordPress Plugins
The 16-Step Checklist for Securing Your WordPress Site

Related Projects

Hummingbird Pro

Everything you need to…

Defender Pro

Regular security scans, vulnerability…

Snapshot Pro

Make and schedule incremental…

Smush Pro

User's choice, award-winning, and…

Newsletter art

Get fresh WP updates directly to your inbox. Whip newsletter logo.

By clicking subscribe I consent to receiving product updates, news, and future contest emails from WPMU DEV.

Your turn... Cancel reply

Create a free account to post your comment

No credit card required or any silliness like that, we’ll take you straight to your comment
  • Already a Member? Sign In

Stay in the WordPress loop!

Keep on the pulse with WPMU DEV and WordPress newsletters
The Whip
WPMU DEV

Login to post your comment

  • Create a free account
  • Trouble logging in?
 

The Best Hosting

In The WordPress

The Best Hosting in the WordPress World!

View hosting plans Find out more about Hosting
Trustpilot
Resources
  • Contact
  • Pricing
  • The Team
  • System Status
  • Documentation
  • Free Plugins
  • WordCamp Events
  • Hello, WP! Podcast
  • Hosting Comparison
Recent Blog Posts
  • The 16-Step Checklist for Securing Your WordPress Site
    The 16-Step Checklist for Securing Your WordPress Site

    When you’re rushing to meet a deadline, properly securing your WordPress site might…

  • DDoS Protection Guide - How to Help Protect Your WordPress Site From Attacks
    DDoS Protection Guide - How to Help Protect Your WordPress Site From Attacks

    A DDoS attack on your WordPress site can grind it to a halt…

  • How To Scan Your WordPress Site For Malware
    How To Scan Your WordPress Site For Malware

    If your WordPress site is infected with malware, you’re at risk of server…

© 2004-2021 Project by Incsub | Terms & Privacy

Trustpilot

The Most 5-Star Reviews

WPMU DEV has more 5-star reviews than any other WordPress company, find out why with a 7-day free trial today!

Get Started Find out more
Page speed image

Almost There!

Just enter your email address and we’ll send you a link to your free content. You’ll also be taken straight to the video after hitting the button below. Enjoy!

Something went wrong, please try again later.
* WPMU DEV respects your privacy and we’ll only use the details provided to send you relevant content. You can unsubscribe from our communications at any time. Check out our Privacy Policy for more information.
Try Free For 7 Days
Hey you! Join our mailing list for free WordPress tips and resources!
Something went wrong!

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

By clicking subscribe I consent to receiving product updates, news, and future contest emails from WPMU DEV.