Create new post WordPress programmatically with custom meta fields

How can you create and insert new posts containing already filled Advanced Custom Fields programmatically into your database?

  1. Say you have an ACF group with 3 fields each of a different type
    • description (type Text)
    • image (type Image)
    • categories (type Taxonomy)
  2. prepare a basic post
$my_post = array(
        'post_title'    => 'My post',
        'post_content'  => 'This is my post.',
        'post_status'   => 'publish',
        'post_author'   => 1
  1. insert post and keep the created post id
    $post_id = wp_insert_post( $my_post );

  1. then update values of custom fields using the post id
    // description (text type field)
    update_field('field_5629f95fc4108', 'description for post', $post_id);

    // image (Image type field)
    $image_id = array(1, 2, 3);
    update_field('field_5621199730caa', $image_id, $post_id);

    // categories (Taxonomy field type)
    $categories_ids = array(1, 2, 3);
    update_field('field_56211b33d0018', $categories_ids, $post_id);

… Or it can be done using the following code:

To enter a new post for a custom type

$post_id = wp_insert_post(array (
   'post_type' => 'your_post_type',
   'post_title' => $your_title,
   'post_content' => $your_content,
   'post_status' => 'publish',
   'comment_status' => 'closed',   // if you prefer
   'ping_status' => 'closed',      // if you prefer


After inserting the post, a post id will be returned by the above function. Now if you want to enter any post meta information w.r.t this post then following code snippet can be used.

if ($post_id) {
   // insert post meta
   add_post_meta($post_id, '_your_custom_1', $custom1);
   add_post_meta($post_id, '_your_custom_2', $custom2);
   add_post_meta($post_id, '_your_custom_3', $custom3);

Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *