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);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$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>';
}
else
{
echo 'ERROR: ' .$title . ' ('.$street.') did not update successfully! Please edit this manually. <br>';
}
endforeach;
}