USharing
开放博客

WP insert post PHP function and Custom Fields

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

来源:

WP insert post PHP function and Custom Fields

赞(0) 打赏
未经允许不得转载:USharing » WP insert post PHP function and Custom Fields

觉得文章有用就打赏一下文章作者

微信扫一扫打赏