wordpress insert post data and custom fields

Simple 3 steps:
1. create post basic values array of data

$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',
);

2 insert post data and get returned post id
$the_post_id = wp_insert_post( $my_post );
3. use same returned post id to add customfields value.


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 );
}
}

__update_post_meta( $the_post_id, 'my-custom-field', 'my_custom_field_value' );

contact us