https://nicola.blog/2017/03/01/post-meta-get-value/

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, 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 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 true.
Here is a usage example:

<?php
// Get the value of the post meta with name `_my_post_meta_name`
$post_meta_value = get_post_meta( $post->ID, ‘_my_post_meta_name’, true );
// Print the post meta value
printf( ‘The value of my post meta is %s’, $post_meta_value ); ?>

view rawfunctions.php hosted with ❤ by GitHub

Adding and Updating Post Meta

Saving a custom field value in the database 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 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 add_post_meta().

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.

Loading