Wednesday 15 October 2014

Add Custome Meta Data Field in WordPress

Default Usage

$post_id='12';
$mata_value ='field value'
<?php add_post_meta( $post_id, 'my_key', $mata_value); ?>

Adding or Updating a Unique Custom Field

Adds a new custom field if the key does not already exist, or updates the value of the custom field with that key otherwise.
 <?php add_post_meta( $post_id, 'fruit', 'banana', true ) || update_post_meta( $post_id, 'fruit', 'banana' ); ?>
The following will have the same effect:
<?php
// Add or Update the meta field in the database.
if ( ! update_post_meta ($post_id, 'fruit', 'banana') ) { 
 add_post_meta($post_id, 'fruit', 'banana', true ); 
}; 
?> 

Other Examples

Adds a new custom field only if a custom field with the given key does not already exists:
<?php add_post_meta( $post_id, 'my_key', '47', true ); ?>
Adds several custom fields with different values but with the same key 'my_key':
<?php add_post_meta( $post_id, 'my_key', '47' ); ?>
<?php add_post_meta( $post_id, 'my_key', '682' ); ?>
<?php add_post_meta( $post_id, 'my_key', 'The quick, brown fox jumped over the lazy dog.' ); ?>
...

1 comment: