Home › Forums › ACF PRO › Save certain Google Maps data into custom field › Reply To: Save certain Google Maps data into custom field
This worked for me. Be sure to set your Google Maps API key beforehand if you have not done so already.
replace “pickup_” with your custom field keys.
/**
* Save Google Map field data to custom fields in ACF
*
* This snippet hooks into the ACF save process to extract the data
* from a Google Map field and save it to custom fields for address,
* city, state, zip code, latitude, and longitude.
*
* @param int $post_id The ID of the post being saved.
*/
function save_google_map_data_to_custom_fields($post_id) {
// Check if this is an autosave or if the user has permission to save
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check user permissions
if (!current_user_can('edit_post', $post_id)) {
return;
}
// Get the Google Map field value
$google_map_data = get_field('your_google_map_field_name', $post_id);
// Check if the Google Map field has data
if ($google_map_data && is_array($google_map_data)) {
// Extract data from the Google Map field
$street_number = isset($google_map_data['street_number']) ? $google_map_data['street_number'] : '';
$street_name = isset($google_map_data['street_name']) ? $google_map_data['street_name'] : '';
$city = isset($google_map_data['city']) ? $google_map_data['city'] : '';
$state = isset($google_map_data['state']) ? $google_map_data['state'] : '';
$post_code = isset($google_map_data['post_code']) ? $google_map_data['post_code'] : '';
$country = isset($google_map_data['country']) ? $google_map_data['country'] : '';
$latitude = isset($google_map_data['lat']) ? $google_map_data['lat'] : '';
$longitude = isset($google_map_data['lng']) ? $google_map_data['lng'] : '';
// Save to custom fields
update_field('pickup_address', trim("$street_number $street_name"), $post_id);
update_field('pickup_city', $city, $post_id);
update_field('pickup_state', $state, $post_id);
update_field('pickup_zipcode', $post_code, $post_id);
update_field('pickup_country', $country, $post_id); // If you want to save the country as well
update_field('pickup_latitude', $latitude, $post_id);
update_field('pickup_longitude', $longitude, $post_id);
}
}
// Hook into ACF save process
add_action('acf/save_post', 'save_google_map_data_to_custom_fields');
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.