How To Use WordPress get_post_meta

WordPress comes along with a function called get_post_meta and it is used to get custom field values for different posts. But before we get into it, here’s a brief overview of what custom fields in WordPress are.
What is a custom field?
Custom fields basically mean the data that describe your posts. Generally, we call it as Meta Data or Post Meta. Suppose you have listed an item for sale on WooCommerce, then the product type or its pricing is the custom field.
Such data is stored in the database table called wp_postmeta.
In simpler words, custom field is the data that you can use to differentiate your posts on a website.
How To Get Custom Fields Values With get_post_meta?
As we have mentioned above, get_post_meta is a WordPress function used to get custom field values. Note that the function can be used for a type of post, page or product, etc.
Here are the three parameters that get_post_meta will accept.
- $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’s a working example of get_post_meta
<?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 );
Adding and Updating Post Meta
To add or save a custom field in a database, you need to use the function add_post_meta().
Here are the 4 parameters that are accepted.
$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.
As for updating the value of an existing custom field, you need to use the function update_post_meta()
Deleting The Custom Field Values
Deleting the custom fields is as easy as adding them up. Here you need to use the function delete_post_meta().
Check out the three parameters it will accept.
$post_id: The ID of the post.
$key: The name of the custom field.
$value (optional): The value of the custom field.