Search code examples
wordpressadvanced-custom-fields

ACF fields value not available until saving post manually


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().


Solution

  • 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....