Languages: English • 中文(简体) • Русский • Español • 日本語 Português do Brasil • 한국어 • (Add your language)
Adds a custom field (also called meta-data) to a specified post which could be of any post type. A custom field is effectively a key–value pair.
Note that if the given key already exists among custom fields of the specified post, another custom field with the same key is added unless the $unique argument is set to true, in which case, no changes are made. If you want to update the value of an existing key, use the update_post_meta() function instead.
<?php add_post_meta($post_id, $meta_key, $meta_value, $unique); ?>
<?php add_post_meta( 68, 'my_key', 47 ); ?>
Add a new custom field if the key does not already exist, or updates the value of the custom field with that key otherwise.
<?php if ( ! add_post_meta( 7, 'fruit', 'banana', true ) ) { update_post_meta( 7, 'fruit', 'banana' ); }
Adds a new custom field only if a custom field with the given key does not already exist:
<?php add_post_meta( 68, 'my_key', '47', true ); ?>
Adds several custom fields with different values but with the same key 'my_key':
<?php add_post_meta( 68, 'my_key', '47' ); ?> <?php add_post_meta( 68, 'my_key', '682' ); ?> <?php add_post_meta( 68, 'my_key', 'The quick, brown fox jumped over the lazy dog.' ); ?> ...
For a more detailed example, see the post_meta Functions Examples page.
If you are a plugin or theme developer and you are planning to use custom fields to store parameters related to your plugin or template, it is interesting to note that WordPress will not show custom fields which have keys starting with an "_" (underscore) in the custom fields list on the post edit screen or when using the the_meta() template function. This can be for example used to show these custom fields in an unusual way by using the add_meta_box() function.
The following example:
<?php add_post_meta( 68, '_color', 'red', true ); ?>
will add a unique custom field with the key name '_color' and the value 'red' but this custom field will not display in the post edit screen.
In addition, if the $meta_value argument is an array, it will not be displayed on the page edit screen, even if you don't prefix the key name with an underscore.
An alternative to the use of an "_" (underscore) is to use the filter is_protected_meta.
Because meta values are passed through the stripslashes() function, you need to be careful about content escaped with \ characters. You can read more about the behavior, and a workaround example, in the update_post_meta() documentation.
add_post_meta() is located in wp-includes/post.php
Since 1.5.0
Custom Fields: the_meta(), get_post_meta(), add_post_meta(), update_post_meta(), delete_post_meta(), get_post_custom(), get_post_custom_values(), get_post_custom_keys() (See Also: post_meta Function Examples)