Florian Boudot
Florian Boudot

Reputation: 1055

Insert new WordPress post with custom meta fields programmatically

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

Upvotes: 1

Views: 4191

Answers (1)

Florian Boudot
Florian Boudot

Reputation: 1055

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

Upvotes: 7

Related Questions