add_post_meta

Add meta data field to a post.

Description

(int|false) add_post_meta( (int) $post_id, (string) $meta_key, (mixed) $meta_value, (bool) $unique = false ); 

Post meta data is called Custom Fields on the Administration Screen.

Returns (int|false)

Meta ID on success, false on failure.

Parameters (4)

0. $post_id (int)
The post id.
1. $meta_key (string)
Metadata name.
2. $meta_value (mixed)
Metadata value. Must be serializable if non-scalar.
3. $unique — Optional. (bool) => false
Whether the same key should not be added. Default false.

Usage

  1. if ( !function_exists( 'add_post_meta' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // The post id. 
  5. $post_id = -1; 
  6.  
  7. // Metadata name. 
  8. $meta_key = ''; 
  9.  
  10. // Metadata value. Must be serializable if non-scalar. 
  11. $meta_value = null; 
  12.  
  13. // Optional. Whether the same key should not be added. 
  14. // Default false. 
  15. $unique = false; 
  16.  
  17. // NOTICE! Understand what this does before running. 
  18. $result = add_post_meta($post_id, $meta_key, $meta_value, $unique); 
  19.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/post.php  
  1. function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) { 
  2. // Make sure meta is added to the post, not a revision. 
  3. if ( $the_post = wp_is_post_revision($post_id) ) 
  4. $post_id = $the_post; 
  5.  
  6. return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);