wpmudev wpmudev

Proudly Australian owned & operated

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

    Manage unlimited sites with our free tools

    Basic

    1 site, pro tools/plugins, 5GB CDN

    Standard

    3 sites, pro tools/plugins, 10GB CDN

    Freelancer

    10 sites, pro tools/plugins, 20GB CDN

    Agency

    Everything, unlimited sites, free hosting credits

    Compare Plans
    Featured Plugins
    The Hub Client

    White label WPMU DEV

    Smush Pro

    Optimize unlimited images

    Hummingbird Pro

    Build a faster website

    SmartCrawl Pro

    Boost your website PageRank

    View all plugins
    Services
    The Hub

    All you need to manage all your WP sites

    Hosting

    Next generation managed WP Hosting

    Clients & Billing

    Invoices, subscriptions & client management

    White Label

    Rebrand plugins, reports & client portals

    Discover
    • Cloning
    • Email
    • Migration
    • Multisite
    • Automated Updates
    • Forms & Quizzes
    • Backups
    • Analytics
    • Monitor
    • DNS
    • WAF
    • Security
    • Translations
    • Configs
    • CDN
    • Opt-ins & Popups
    • Documentation
    • Support
    • Community
    • Roadmap
  • The Hub
  • Pro Plugins Pro Plugins Submenu
    Close Plugins Submenu All Plugins
    Featured Plugins
    The Hub Client

    White label WPMU DEV

    Smush Pro

    Image optimizer

    Hummingbird Pro

    Page speed optimizer

    SmartCrawl Pro

    SEO optimization

    Plugins
    WPMU DEV Dashboard

    Connect, manage & support

    The Hub Client

    White label WPMU DEV

    Smush Pro

    Image optimizer

    Hummingbird Pro

    Page speed optimizer

    SmartCrawl Pro

    SEO optimization

    Snapshot Pro

    Schedule backups

    Defender Pro

    Security

    Forminator Pro

    Forms builder

    Hustle Pro

    Opt-ins & Popups

    Branda Pro

    White label WordPress

    Beehive Pro

    Customise Google Analytics

    Shipper Pro

    Move WP sites with a click

    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

    Hosting Backups

    Disaster-proof backups

  • Migrate to us
  • Blog
  • Pricing
Log In
WPMU DEV Logo
Log in
Products & Services
Everything WPMU DEV
Free
Basic
Standard
Freelancer
Agency
Feature Plugins
Smush Pro
Hummingbird Pro
Defender Pro
Smarcrawl Pro
Services
The Hub
Hosting
Clients & Billing
White Label
Discover
Cloning
Email
Migration
Multisite
Automated Updates
Forms & Quizzes
Backups
Analytics
Monitor
DNS
WAF
Security
Translations
Configs
CDN
Opt-ins & Popups
Documentation
Support
Community
Roadmap
The Hub
Pro Plugins
All Plugins
WPMU DEV Dashboard
The Hub Client
Smush Pro
Hummingbird Pro
Defender Pro
SmartCrawl Pro
Snapshot Pro
Forminator Pro
Hustle Pro
Branda Pro
Shipper Pro
Beehive Pro
Integrated Video Tutorials
Hosting
Hosting
WAF
DNS
Email
Hosting Comparison
Cloning
Migration
Migrate to us
Pricing
Blog
  • Blog
  • Development
  • Creating Custom Fields Manually...
WPMU DEV Logo Creating Custom Fields Manually in WordPress
User Gravatar Daniel Pataki Daniel Pataki   – March 22, 2022
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
    • 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.
Tags:
  • custom fields
  • metadata
Share this article
User GravatarDaniel 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.
wpmudev
The DEV’s Pixels
Shareable, fun, & free WP comics.
Check them out
wpmudev

Build A Better WordPress Business

Take a quick tour Play btn
Start 7-Day Free Trial
Follow Us
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
Full Site Editing Is the Future of WordPress. Can You FSE It?

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 punny WP news! P.S. We keep your email 100% private and do not spam :)
OR
OR

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

Login to post your comment

  • Create a free account
  • Trouble logging in?
 
Learn more
Trustpilot
Graphic of hand giving a high five

Our biggest discounts happen over email

Be first to know about our newest product releases and sales - including this year’s Black Friday sale which is set to be our biggest yet!

By clicking subscribe I consent to receiving relevant WPMU DEV content! P.S. We keep your email 100% private and do not spam :)

WPMU DEV

Site Management Hosting Pro Plugins White Label

Products

Free Plugins Configs Automation Emails Multisite CDN

Services

Migration Client & billing Security WAF Monitor Analytics

Discover

Compare Hosting The DEV's Pixels

Resources

Blog Support Forums Documentation Roadmap Translations

About

Careers System Status Contact
Trustpilot
Made for web developers, by web developers
wpmudev Proudly Australian
Terms Privacy
Sign up free
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 fresh blog posts! P.S. we keep your email 100% private and do not spam :)