Wordpress - How to update custom fields using the wp_insert_post() function?
If you read the documentation for wp_insert_post
, it returns the post ID of the post you just created.
If you combine that with the following function __update_post_meta
(a custom function I acquired from this site and adapted a bit)
/**
* Updates post meta for a post. It also automatically deletes or adds the value to field_name if specified
*
* @access protected
* @param integer The post ID for the post we're updating
* @param string The field we're updating/adding/deleting
* @param string [Optional] The value to update/add for field_name. If left blank, data will be deleted.
* @return void
*/
public function __update_post_meta( $post_id, $field_name, $value = '' )
{
if ( empty( $value ) OR ! $value )
{
delete_post_meta( $post_id, $field_name );
}
elseif ( ! get_post_meta( $post_id, $field_name ) )
{
add_post_meta( $post_id, $field_name, $value );
}
else
{
update_post_meta( $post_id, $field_name, $value );
}
}
You'll get the following:
$my_post = array(
'post_title' => $_SESSION['booking-form-title'],
'post_date' => $_SESSION['cal_startdate'],
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_type' => 'booking',
);
$the_post_id = wp_insert_post( $my_post );
__update_post_meta( $the_post_id, 'my-custom-field', 'my_custom_field_value' );
You can simple add the 'add_post_meta' after the 'wp_insert_post'
<?php
$my_post = array(
'post_title' => $_SESSION['booking-form-title'],
'post_date' => $_SESSION['cal_startdate'],
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_type' => 'booking',
);
$post_id = wp_insert_post($my_post);
add_post_meta($post_id, 'META-KEY-1', 'META_VALUE-1', true);
add_post_meta($post_id, 'META-KEY-2', 'META_VALUE-2', true);
?>