Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Created January 23, 2019 02:24
Show Gist options
  • Save MogulChris/b7c2bf3b8fa864b96880bfe38c0209ae to your computer and use it in GitHub Desktop.
Save MogulChris/b7c2bf3b8fa864b96880bfe38c0209ae to your computer and use it in GitHub Desktop.
Programmatically update ACF Google Maps fields
<?php
//You need an API key and an address (as a string) to geocode
//ACF Google Maps field data looks like:
/*
array(
'address' => '123 My Street, Mytown, Mycountry, Mypostcode',
'lat' => '123.45678',
'lng' => '-125.67890',
)
*/
$api_key = 'YOUR_API_KEY_HERE';
$address = urlencode($address_string);
$post_id = 123;
$response = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=$api_key");
$response = json_decode($response,true);
if(!empty($response['results'][0]['geometry']['location'])){
$geo = $response['results'][0]['geometry']['location'];
$formatted_address = $response['results'][0]['formatted_address'];
$location = array('address' => $formatted_address, 'lat' => $geo['lat'], 'lng' => $geo['lng']);
update_field('YOUR_FIELD_KEY', $location, $post_id);
}
@iffikhan30
Copy link

Supperb

@johannlucas
Copy link

Thank you, great time saved.

@chrisokwakol
Copy link

hey so the field is updating, i can see it when i var_dump the acf field but the address on the map in the backend isn't updating. how do i go about this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment