4
votes

I have some custom post type "video" and I added some custom ACF fields to it ("video_path", "author_name" and "audio_author"). I'm generating posts in that type programmatically like this:

$video_post_params = array(
  'post_title'    => wp_strip_all_tags($video_title),
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_type'     => 'video'
);
$video_id  = wp_insert_post( $video_post_params );
update_field('video_path', $video_path, $video_id);
update_field('author_name', $video_author, $video_id);
update_field('audio_author', $audio_author, $video_id);

All values are inserted well - when I open the post in back-end everything is fine. However, when I try to use those values, I don't get anything?!?

I'm reading values from template files like this:

get_field('video_path', $video_id)

And if I open the post and just save it without any change everything starts working normally and I'm getting post ACF fields normally after that. Posts created manually, from back-end are working well all the time.

What I'm doing wrong? Do I need some extra step when generating posts from code?

The issue is reported here: http://support.advancedcustomfields.com/forums/topic/programmatic-post-insertion-acf-fields-and-the-save_post-hook/

But that solution is obviously not working for me - my update_field() functions already are immediately after wp_insert_post().

4

4 Answers

6
votes

Found it!

When inserting ACF field value field key must be used. If key name is used instead, as I did, everything is inserted well at first look, but value isn't available until post is saved manually. So it's like:

update_field('field_56e683ab6265f', $video_path, $video_id);
update_field('field_56e68415b5c4b', $video_author, $video_id);
update_field('field_56e6842d58740', $audio_author, $video_id);

What a mess....

1
votes

If you want to use the field name instead of the field key, you can use add_post_meta

For example:

add_post_meta($video_id, 'video_path', $video_path, true);
add_post_meta($video_id, 'author_name', $video_author, true);
add_post_meta($video_id, 'audio_author', $audio_author, true);
0
votes

With ACF5 you have to use not post id, but post object, lake that:

update_field('field_56e683ab6265f', $video_path, $video);
update_field('field_56e68415b5c4b', $video_author, $video);
update_field('field_56e6842d58740', $audio_author, $video);
0
votes

I had the same problem, and I correct it with simply add do_action('acf/save_post', $postID); at the end of the script, and that's all…