How to Use update_post_meta in WordPress: Syntax and Examples
Use
update_post_meta($post_id, $meta_key, $meta_value, $prev_value) to add or update custom metadata for a post in WordPress. It updates the meta value if the key exists or adds it if not, helping you store extra information linked to posts.Syntax
The update_post_meta function updates or adds metadata for a post. It takes four parameters:
- $post_id: The ID of the post to update.
- $meta_key: The name of the meta field.
- $meta_value: The new value to store.
- $prev_value (optional): The old value to check before updating.
If $prev_value is provided, only the meta with that value will be updated.
php
update_post_meta( int $post_id, string $meta_key, mixed $meta_value, mixed $prev_value = '' ) : bool
Example
This example shows how to update a post's custom field called 'rating' to 5. If the 'rating' meta does not exist, it will be added.
php
<?php $post_id = 123; // Replace with your post ID $meta_key = 'rating'; $meta_value = 5; $updated = update_post_meta($post_id, $meta_key, $meta_value); if ($updated) { echo "Meta updated or added successfully."; } else { echo "Meta value was already set to this value."; } ?>
Output
Meta updated or added successfully.
Common Pitfalls
Common mistakes when using update_post_meta include:
- Using the wrong
$post_id, which causes no update. - Not checking the return value, so you don't know if the meta was changed.
- Confusing
update_post_metawithadd_post_metawhich only adds and fails if the key exists. - Passing incorrect data types for
$meta_value, which can cause unexpected results.
php
<?php // Wrong: Using add_post_meta when you want to update add_post_meta(123, 'rating', 5); // Fails if 'rating' exists // Right: Use update_post_meta to add or update update_post_meta(123, 'rating', 5); ?>
Quick Reference
| Parameter | Description | Required | Type |
|---|---|---|---|
| $post_id | ID of the post to update meta for | Yes | int |
| $meta_key | Name of the meta field | Yes | string |
| $meta_value | Value to set for the meta field | Yes | mixed |
| $prev_value | Optional old value to check before updating | No | mixed |
Key Takeaways
Use update_post_meta to add or update custom fields for posts in WordPress.
Always provide the correct post ID and meta key to avoid silent failures.
Check the function's return value to confirm if the meta was changed.
Avoid using add_post_meta when you want to update existing meta values.
Pass the correct data type for meta values to ensure expected behavior.