Codex

Function Reference/add post meta

Contents

Description

add_post_meta adds a custom (meta) field to the specified post.

If the $unique parameter is set to true and the specified meta key already exists, the function returns false and makes no changes; otherwise, it returns true.

Usage

 <?php add_post_meta($post_id$meta_key$meta_value$unique); ?> 

Examples

Default Usage

<?php add_post_meta(68, 'my_key', 47); ?>

Adding or updating a unique field

Adds a new field if the key doesn't exist, or updates the existing field. (UPDATE: If the forth parameter of add_post_meta is set to true, the field will not be update if it already exists (tested on WP 2.6.2). Use if (!update_post_meta(...)) add_post_meta(...))

 <?php add_post_meta(7, 'fruit', 'banana', true) or update_post_meta(7, 'fruit', 'banana'); ?>

Other Examples

If you wanted to make sure that there were no fields with the key "my_key", before adding it:

<?php add_post_meta(68, 'my_key', '47', true); ?>

To add several values to the 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, go to the post_meta Functions Examples page.

Making a "Hidden" Custom Field

If you are a plugin / 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 wont show keys starting with an "_" (underscore) in the custom fields list at the page / post editing page. That being said, it is a good practice to use an underscore as the first character in your custom parameters, that way your settings are stored as custom fields, but they won't display in the custom fields list in the admin UI.

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 page / post editing page.

Parameters

$post_id
(integer) (required) The ID of the post to which you will add a custom field.
Default: None
$meta_key
(string) (required) The key of the custom field you will add.
Default: None
$meta_value
(string) (required) The value of the custom field you will add.
Default: None
$unique
(boolean) (optional) Whether or not you want the key to be unique. When set to true, this will ensure that there is not already a custom field attached to the post with $meta_key as it's key, and, if such a field already exists, the key will not be added.
Default: false

Related

delete_post_meta(), get_post_meta(), update_post_meta(), get_post_custom(), get_post_custom_values(), get_post_custom_keys()