Advanced Custom Fields: update_field not working?

It does work.

If you’re building a wordpress function that programmatically creates or updates posts while using update_field() you may notice that to retrieve that data elsewhere using the get_fields() function it turns up a blank.

For example when you do this

// Create post object
$my_post = array(
 'post_title' => 'My post',
 'post_content' => 'This is my post.',
 'post_status' => 'publish',
 'post_author' => 1
);

// Insert the post into the database
$post_id = wp_insert_post( $my_post );

// Add field value
update_field( "field_name_or_id", "I am a value!", $post_id );

Same goes for simply updating a bunch of fields without creating a new post

This is simple enough and its doing what you’d hoped it would do, however, the problem comes when you try to retrieve the data using get_field() or get_fields(), it simply spits out a blank UNLESS you have gone directly into the WordPress admin area and updated or resaved the post you just created.

I a few years back I found the solution but I don’t remember where on the net i found it so im posting it here.

// This doesn't seem to work so don't use this
$fields = get_fields();


// Instead use the built in wordpress function to grab the data
$fields = get_post_custom($post_id);

 

Hope this solves any headaches

Leave a Reply

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