Posted on

What is a Post Meta and How to Get Its Value

Did you know about post meta in WordPress? Most probably you already use them and you don’t know that they are called post meta.

Some time ago I wrote an article about how to add fields to products in WooCommerce. Those fields are custom product fields, and their value 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 you what they are and how to get them!

What Is a Post Meta?

Post meta are also known as metadata or custom fields in WordPress. You probably heard of custom fields already.

They can be defined as data that describe posts. For example, the post type is a meta data, or the post format. In WooCommerce, the price is a post meta, or the product type.

Most of the time they are stored in the database table wp_postmeta, except for some specific post data, like the post type.

These post 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 Post Meta

WordPress has a function to get post metadata, get_post_meta().

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 post meta.
  • $key – The name of the post meta. Usually they start with a _ indicating that it’s a hidden post meta.
  • $single (optional) – Indicates if the post meta 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 true.

Here is a usage example:

Adding and Updating Post Meta

Adding a post meta is as easy as getting it. The function to use is add_post_meta().

It accepts four parameters:

  • $post_id – The post ID.
  • $key – The meta name.
  • $value – The value of the meta.
  • $single (optional) – Whether the same key should not be added if it already exists.

To update the value of an existing post meta use the function update_post_meta() in the same way of the function add_post_meta().

Deleting Post Meta

As you might guess, the function to delete post meta is delete_post_meta() and it accepts three parameters:
* $post_id – The ID of the post.
* $key – The name of the meta.
* $value (optional) – The value of the meta.

Leave a Reply

Your email address will not be published. Required fields are marked *