add_post_meta() – Function description, parameters and basic usage

Description:

add_post_meta is a WordPress function which Adds a custom field value to a post by given ID. Very useful for storing additional data to post(like dates for sorting, thumbnail image, links etc..). I`m actively using it with custom post types.

Parameters:

$post_id (required) – The id of the post on which you want to add the custom field

$meta_key (required) – The name(or key) of the custom field you want to add

$meta_value (required) – the value of the

Basic usage example:

$postID = $post->ID;
add_post_meta($postID, 'example_custom_key', 'example custom value');
//This will add custom field to with name: "example_custom_key" and value: "example custom value" to the post with id $postID
//If you want the custom field to be unique run the function like this:
add_post_meta($postID, 'example_custom_key', 'example custom value', true);

A good more advanced example of using add_post_meta() will be to add a custom value to WordPress post on post publish(save_post action):

add_action('save_post', 'save_custom');
function save_custom(){
global $post;
$generated_value = strtotime("now");
add_post_meta($post->ID, "date", $generated_value, true);
}
//This function will create a custom field named date containing the current date as a value
About Pavel Petrov 2 Articles |  21 How-tos
Pavel is a senior developer for the last 7 years, with extended interest in Linux administration, WordPress and Symfony.

Be the first to comment

Leave a Reply

Your email address will not be published.


*