How can you create and insert new posts containing already filled Advanced Custom Fields programmatically into your database?
- Say you have an ACF group with 3 fields each of a different type
- description (type Text)
- image (type Image)
- categories (type Taxonomy)
- prepare a basic post
1 2 3 4 5 6 | $my_post = array( 'post_title' => 'My post', 'post_content' => 'This is my post.', 'post_status' => 'publish', 'post_author' => 1 ); |
- insert post and keep the created post id
1 | $post_id = wp_insert_post( $my_post ); |
- then update values of custom fields using the post id
1 2 3 4 5 6 7 8 9 10 | // 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
1 2 3 4 5 6 7 8 | $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.
1 2 3 4 5 6 | 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); } |