Cyborg
Cyborg

Reputation: 1447

WordPress - How to add/update post_meta (Custom Fields)?

I have made this simple code to add a new POST to WordPress DB (outside LOOP):

include_once './wp-config.php';
include_once './wp-load.php';
include_once './wp-includes/wp-db.php';

$upname = 'TestName';
$updescription = 'Description';

  // Create post object
  $my_post = array();
  $my_post['post_title'] = $upname;
  $my_post['post_content'] = $updescription;
  $my_post['post_status'] = 'draft';
  $my_post['post_author'] = 1;

  if (current_user_can( 'manage_options' )) {

  // Insert the post into the database
  wp_insert_post( $my_post );  
  echo '<br /><b>The Advertisement is saved as Draft!</b>';
  } else {
  echo '<br /><b>You are NOT logged in, login to continue!</b>';
  }

It works 100% but now I wish to add 2 custom fields: "phone_num" and "birth_date"

How can I add custom fields within this code?

Upvotes: 0

Views: 1439

Answers (2)

Krunal Shah
Krunal Shah

Reputation: 2101

You should use this, it will helps you more.

I have use this one, and it works fine.

// Insert the post into the database
$post_id =  wp_insert_post( $my_post );
add_post_meta($post_id,'phone_num',$upphone); or 
    update_post_meta($post_id,'phone_num',$upphone);
add_post_meta($post_id,'birth_date',$upbirthdate); or 
     update_post_meta($post_id,'birth_date',$upbirthdate);

Thanks.

Upvotes: 0

Cyborg
Cyborg

Reputation: 1447

I found a solution and this worked for me :-)

In my code I updated/replaced:

// Insert the post into the database
wp_insert_post( $my_post );

With this:

// Insert the post into the database
$post_id =  wp_insert_post( $my_post );
update_post_meta($post_id,'phone_num',$upphone);
update_post_meta($post_id,'birth_date',$upbirthdate);

Upvotes: 2

Related Questions