update_post_meta and update_field ony working when saving the post

All we need is an easy explanation of the problem, so here it is.

I use Advanced Custom Fields (ACF) to store data in a custom field. I had latitude and longitude information stored separately, but I they need to be in one custom field so I made the function below. $query just queries all the relevant posts.

<?php 
$query = query_custom_posts(); if($query->have_posts()): 
while ($query->have_posts()): $query->the_post();
if(get_field('map_lat') && get_field('map_lng')):

$lat = get_field('map_lat');
$long = get_field('map_lng');
$coord = $lat.','.$long;
$post_id = get_the_ID();

update_post_meta($post_id, 'map_coor', $coord);


endif; endwhile; wp_reset_query(); endif;

?>

Now the function above works. The field map_coor gets populated with the lat and long separated by a comma (I can see the information in the field).

The weird thing is that if I use get_field('map_coor') on the front-end nothing shows up. If I save the corresponding post, then the info DOES show up.

In the function above I also tried to use the function update_field (from ACF) like this: update_field($post_id, 'map_coor', $coord) but the problem is still there.

So my question is; do I need to alter the function above or just run a function which saves all posts? If the latter is the case; how do I do that? I’ve found the hook save_posts but I’m not sure how to let it run through all the posts.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The problem is that the function update_field from ACF works a little bit different from update_post_meta. Can you see it?

update_post_meta( $post_id, $meta_key, $meta_value, $prev_value );
update_field( $field_key, $value, $post_id );

If you use update_post_meta you should in my opinion use get_post_meta to get the meta. If you use update_field you should use the_field or get_field because ACF stores the key/values-pairs in a slightly different way.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply