I need to update the lat and lng meta fields for my posts automatically, based on the address entered from a CSV import. For some reason, the number of failed updates changes sometimes when I run my plugin that handles this. Any insights as to why this may be? Here's the function that handles the update. It relies on Google Maps to provide me with JSON data, which I decode.

function jwd_update_all_stores_action()

 echo '<h3>Results Log:</h3>';

$posts = get_posts( array('post_type' => 'wpsl_stores', 'numberposts' => -1 ) );

foreach ( $posts as $post ):

  //$my_post->post_content = 'This is the updated content.';

  $id = $post->ID;
  $long = get_post_meta($id, 'wpsl_lng', true);
  $lat = get_post_meta($id, 'wpsl_lat', true);

  $title = get_the_title($id);
  $street = get_post_meta($id, 'wpsl_address', true);
  $city = get_post_meta($id, 'wpsl_city', true);
  $state = get_post_meta($id, 'wpsl_state', true);

  $address = $street .', '. $city .', '. $state;
  $prepAddr = str_replace(' ','+',$address);
  $output = false;

  if ($geocode){
    $output= json_decode($geocode);

  if ($output && $output->results)
    $new_lat = $output->results[0]->geometry->location->lat;
    $new_long = $output->results[0]->geometry->location->lng;

    update_post_meta( $id, 'wpsl_lng', $new_long );
    update_post_meta( $id, 'wpsl_lat', $new_lat );

    echo $title . ' ('.$street.') updated successfully <br>';
    echo 'ERROR: ' .$title . ' ('.$street.') did not update successfully! Please edit this manually. <br>';




1 Answer 1


Turns out it was an issue with not providing a geocode API! I needed to change



$geocode = file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key='.$api_key);

In other words, there needs to be the key parameter with the API key in that URL. I also removed the sensor parameter, as that does not appear to be needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.