The add_post_meta() WordPress PHP function is used to add a meta field to a specified post.
Usage
To use the add_post_meta() function, you would typically specify the post ID, the meta key, the meta value, and a Boolean for whether the key should be unique.
add_post_meta($post_id, $meta_key, $meta_value, $unique);
Parameters
- $post_id (int): The ID of the post to which you want to add the meta field.
- $meta_key (string): The name of the meta field.
- $meta_value (mixed): The value of the meta field. If the value is non-scalar, it should be serializable.
- $unique (bool): If set to true, the function will not add the meta field if one with the same key already exists. Defaults to false.
More information
See WordPress Developer Resources: add_post_meta()
This function has been a part of WordPress since version 1.5.0. Note that if a meta field with a key starting with an underscore (‘_’) is added, it won’t be shown in the WordPress admin interface.
Examples
Adding a Meta Field
This adds a meta field named ‘color’ with the value ‘blue’ to the post with ID 42.
add_post_meta(42, 'color', 'blue', true);
Adding Multiple Meta Fields
Here, we’re adding multiple meta fields with the same key but different values to a single post.
add_post_meta(42, 'colors', 'blue'); add_post_meta(42, 'colors', 'red'); add_post_meta(42, 'colors', 'green');
Checking Before Adding
This checks if the meta field ‘fruit’ exists for post 7. If not, it adds it; otherwise, it updates it.
if (!add_post_meta(7, 'fruit', 'banana', true)) { update_post_meta(7, 'fruit', 'banana'); }
Deleting a Meta Field
This deletes the meta field ‘color’ from post 42 if its value is ‘blue’.
delete_post_meta(42, 'color', 'blue');
Complete Solution
This function checks if a new value exists for a meta field, and either adds, updates, or deletes it as needed.
function my_update_post_meta($post_id, $meta_key, $new_meta_value) { $meta_value = get_post_meta($post_id, $meta_key, true); if ($new_meta_value && '' === $meta_value) add_post_meta($post_id, $meta_key, $new_meta_value, true); else if ($new_meta_value && $new_meta_value !== $meta_value) update_post_meta($post_id, $meta_key, $new_meta_value, $meta_value); else if ('' === $new_meta_value && $meta_value) delete_post_meta($post_id, $meta_key, $meta_value); }