WordPress Functions

WordPress: update_post_meta function

18 October 2023

Managing custom data associated with posts or pages is a common task, this is where the update_post_meta function comes into play. It’s a powerful tool that allows you to effortlessly handle and update custom metadata for your content, including meta fields and post IDs. With this function, you can seamlessly update existing metadata entries and set new post meta values, ensuring the precision and reliability of your data.

How update_post_meta Works

Using the update_post_meta WordPress function is straightforward and can be immensely useful in managing custom data associated with your WordPress posts or pages. Let’s break down how to use it step by step:

update_post_meta( int $post_id, string $meta_key, mixed $meta_value, mixed $prev_value = '' )
  • $post_id (int): The ID of the post for which you want to update or create metadata.
  • $meta_key (string): The unique identifier for the metadata you want to update or create.
  • $meta_value (mixed): The new value you want to set for the metadata.
  • $prev_value (mixed, optional): The previous value you want to check before updating. If specified, the update will only occur if the existing post meta matches this value. Default is an empty string.
Return Value
  • If the metadata field for the post does not exist, it will be added, and the function will return its ID.
  • If the update is successful, the function will return true.
  • If the update fails or the provided value is the same as the existing metadata, it will return false.

The update_post_meta function operates efficiently behind the scenes to manage post meta field data, relying on the update_metadata function. Here’s a step-by-step explanation of how it works:

function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
// Make sure meta is updated for the post, not for a revision.
$the_post = wp_is_post_revision( $post_id );
if ( $the_post ) {
$post_id = $the_post;
return update_metadata( 'post', $post_id, $meta_key, $meta_value, $prev_value );

1. Check for Post Revision: The function begins by checking if the provided $post_id corresponds to a post revision rather than the actual post. If it is a revision, it redirects the operation to the parent post.

2. Data Sanitization: Before processing, the function ensures that the metadata key and value are sanitized and free from any potential security risks. It uses the wp_unslash and sanitize_meta functions to ensure data integrity.

3. Short-circuit Hook: A hook called update_post_metadata is available for developers to short-circuit the operation based on custom conditions. This allows developers to prevent metadata updates under certain circumstances.

4. Comparison with Previous Value: If the $prev_value parameter is provided, the function checks whether the existing metadata matches this value. If there is a match, the update proceeds; otherwise, it is aborted.

5. Database Query: The function queries the WordPress database to retrieve the IDs of existing metadata entries that match the provided $meta_key and $post_id. If no matching entries are found, it falls back to the add_metadata function to create a new metadata entry.

6. Update or Insert: If existing meta data entries are found, the function updates the values of these entries in the database. If no matching entries exist, it inserts a new metadata entry with the provided key and value.

7. Action Hooks: Throughout the process, various action hooks are triggered, allowing developers to perform custom actions or additional processing before and after metadata updates. These hooks include update_post_meta and updated_post_meta for post-related metadata.

8. Caching: To optimize performance, the function interacts with WordPress caching mechanisms. It clears the cache for the specific post’s metadata to ensure data consistency.

9. Return Values: Depending on the outcome of the operation, the function returns true for a successful update, false for failure, or the ID of the newly added metadata field if it was created during the operation.

The update_post_meta function in WordPress provides a robust way to manage post metadata, offering both update and insert capabilities. It ensures data integrity, allows for custom logic, and leverages caching to optimize performance while maintaining a structured approach to handling meta field data associated with posts.

How to Use update_post_meta

On custom post type:

Let’s say you have a custom post type called “Book” where you want to store additional custom field metadata such as the book’s author and publication year.

// Assuming you've already registered a custom post type 'book'
// Get the post ID of the book you want to update
$book_id = 123; // Replace with the actual post ID of your book
// Define the meta field data
$author_name = "John Doe";
$publication_year = 2023;
// Update the author metadata for the book
update_post_meta($book_id, 'book_author', $author_name);
// Update the publication year metadata for the book
update_post_meta($book_id, 'book_publication_year', $publication_year);

In this example:

  1. You obtain the post ID of the specific book you want to update. Replace 123 with the actual ID of your book post.
  2. You define the post meta data you want to update. Here, we set the author’s name and the publication year.
  3. The update_post_meta function is called twice to update two different metadata fields: book_author and book_publication_year for the specified book post.
  4. After running this code, the metadata for the “Book” custom post with the ID 123 will be updated with the author’s name and publication year.

Inside a WordPress plugin:

Assuming you have a custom post type called “Book,” and you want to update custom field metadata for a book post when a user submits a form:

// Define a function to handle form submissions
function handle_book_form_submission() {
if (isset($_POST['book_id']) && isset($_POST['book_author']) && isset($_POST['book_publication_year'])) {
// Get the data from the form
$book_id = intval($_POST['book_id']);
$author_name = sanitize_text_field($_POST['book_author']);
$publication_year = intval($_POST['book_publication_year']);
// Update the author meta fields for the book
update_post_meta($book_id, 'book_author', $author_name);
// Update the publication year metadata for the book
update_post_meta($book_id, 'book_publication_year', $publication_year);
// Hook the function to a WordPress action, e.g., 'init'
add_action('init', 'handle_book_form_submission');

In this example:

  1. We define a function handle_book_form_submission that handles form submissions.
  2. Inside the function, we check if the necessary data (book_id, book_author, and book_publication_year) has been submitted through the form.
  3. We sanitize and validate the input data to ensure it’s safe to use.
  4. We use the update_post_meta function to update the metadata for the specified book post with the provided author name and publication year.
  5. We hook the handle_book_form_submission function to a WordPress action, in this case, init. You might want to choose a more appropriate action depending on your plugin’s structure and requirements.

This code can be placed within your WordPress plugin file, and it will execute when the form is submitted, updating the metadata for the custom “Book” post type accordingly. Make sure to adjust the field names, validation, and actions to fit your specific plugin and form implementation.

To update multiple values:

You can use the update_post_meta function to update multiple values for a single post by specifying different meta keys. Here’s an example of how to update multiple meta values for a WordPress given post:

// Get the post ID of the post you want to update
$post_id = 123; // Replace with the actual ID of your post
// Define an array of metadata to update
$metadata_to_update = array(
'meta_key_1' => 'New Value 1',
'meta_key_2' => 'New Value 2',
'meta_key_3' => 'New Value 3',
// Loop through the array and update each meta value data
foreach ($metadata_to_update as $meta_key => $meta_value) {
update_post_meta($post_id, $meta_key, $meta_value);

In this example:

  1. Replace $post_id with the actual ID of the post you want to update.
  2. Define an associative array $metadata_to_update, where the keys are the meta value keys you want to update, and the values are the new values you want to set for each meta key.
  3. Use a foreach loop to iterate through the array. Inside the loop, the update_post_meta function is called for each meta key-value pair, updating the post’s metadata accordingly.

This code will update multiple values for the specified post with the given meta keys and values. You can adapt this example to update as many metadata values as needed for a single post.

Using update_post_meta with the WordPress REST API:

// Assume you want to update metadata for a post using the WordPress REST API with authentication
// Define the REST API endpoint URL for the specific post
$api_url = "https://your-website.com/wp-json/wp/v2/posts/123"; // Replace '123' with the actual post ID
// Define the metadata you want to update
$new_metadata = array(
'custom_field_name' => 'New Value for Custom Field',
// Define your WordPress username and password
$username = 'your_username';
$password = 'your_password';
// Prepare the data for the PUT request
$data = array(
'meta' => $new_metadata,
// Create the authentication header
$auth = base64_encode($username . ':' . $password);
$headers = array(
'Authorization' => 'Basic ' . $auth,
'Content-Type' => 'application/json',
// Prepare the request arguments
$args = array(
'method' => 'PUT',
'headers' => $headers,
'body' => json_encode($data),
// Make the request using wp_remote_request
$response = wp_remote_request($api_url, $args);
// Check for errors and display the result
if (is_wp_error($response)) {
echo 'Request error: ' . $response->get_error_message();
} else {
$http_status = wp_remote_retrieve_response_code($response);
if ($http_status === 200) {
echo 'Metadata updated successfully!';
} else {
echo 'Failed to update metadata. HTTP Status Code: ' . $http_status;

In this example:

  • We define WordPress username and password to use for authentication. Replace 'your_username' and 'your_password' with your actual WordPress credentials.
  • We create an authentication header by base64 encoding your username and password.
  • The request arguments are prepared with the authentication headers and the PUT request method.
  • We use wp_remote_request to make the authenticated PUT request to the REST API endpoint.
  • We check for errors using is_wp_error and handle the response based on the HTTP status code as before.

This code demonstrates how to authenticate the REST API request using basic authentication with your WordPress credentials.

Leave a Reply

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


Some of Our Clients

Join clients who enjoy 96% satisfaction

Schedule a Free Strategy Call with a WordPress Expert