Did you know about custom fields in WordPress? Most probably you already use them and you don’t know that they are called so.
Some time ago I wrote an article about how to add fields to products in WooCommerce. Those fields are custom product fields, and their values are post meta.
If you check the article and its comments, you will notice that many people were confused about how to get their value, so let me explain to you what they are and how to get them!
What is a custom field?
Custom fields are also known as metadata or post meta in WordPress.
They can be defined as data that describe posts. For example, the post type is a metadata or the post format. In WooCommerce, the price is a custom field, or the product type.
Most of the time they are stored in the database table
wp_postmeta, except for some specific data, like the post type.
These data simply describe a post, they add details to it so you can do different things based on those details. For example, based on the post type we use the post in a different way or based on the post format, we show the post in a different way.
Getting custom fields values with get_post_meta
WordPress has a function to get custom field values,
This function can be used for any post type, it does not have to be a post, it can be a page, a product, or whatever.
It accepts three parameters:
$post_id– The ID of the post from which we want to get the custom field value.
$key– The name of the custom field. Usually, they start with a
_indicating that it’s a hidden post meta.
$single(optional) – Indicates if the custom field value is an array or not. By default the value for this parameter is
false, but most of the time you will have to use
Here is a usage example:
Adding and Updating Post Meta
Saving a custom field value in the database is as easy as getting it. The function to use is
It accepts four parameters:
$post_id– The post ID.
$key– The custom field name.
$value– The value of the custom field.
$single(optional) – Whether the same key should not be added if it already exists.
To update the value of an existing custom field use the function
update_post_meta() in the same way of the function
Deleting custom fields values
As you might guess, the function to delete custom fields values is
delete_post_meta() and it accepts three parameters:
$post_id – The ID of the post.
$key – The name of the custom field.
$value (optional) – The value of the custom field.