Codex

Function Reference/update post meta

Contents

Description

The function, update post meta(), updates the value of an existing meta key (custom field) for the specified post.

The function returns true upon successful updating, and returns false if the post does not have the meta key specified.

If you want to add a new meta key and value, use the add_post_meta() function instead.

Usage

 <?php update_post_meta($post_id$meta_key$meta_value$prev_value); ?> 

Examples

Default Usage

<?php update_post_meta(76, 'my_key', 'Steve'); ?>

Other Examples

Assuming a post has an ID of 76, and the following 4 custom fields:

[key_1] => 'Happy'
[key_1] => 'Sad'
[key_2] => 'Gregory'
[my_key] => 'Steve'

To change key_2's value to Hans:

<?php update_post_meta(76, 'key_2', 'Hans'); ?>

To change key_1's value from Sad to Happy:

<?php update_post_meta(76, 'key_1', 'Happy', 'Sad'); ?>

The fields would now look like this:

[key_1] => 'Happy'
[key_1] => 'Happy'
[key_2] => 'Hans'
[my_key] => 'Steve'

Note: This function will update only the first field that matches the criteria.

To change the first key_1's value from Happy to Excited:

<?php 
  update_post_meta(76, 'key_1', 'Excited', 'Happy');

  //Or

  update_post_meta(76, 'key_1', 'Excited');

  //To change all fields with the key "key_1":

  $key1_values = get_post_custom_values('key_1', 76);
  foreach ( $key1_values as $value )
    update_post_meta(76, 'key_1', 'Excited', $value);
?>

For a more detailed example, go to the post_meta Functions Examples page.

Parameters

$post_id
(integer) (required) The ID of the post which contains the field you will edit.
Default: None
$meta_key
(string) (required) The key of the custom field you will edit.
Default: None
$meta_value
(string) (required) The new value of the custom field.
Default: None
$prev_value
(string) (optional) The old value of the custom field you wish to change. This is to differentiate between several fields with the same key.
Default: None

Related

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