Skip to content

Instantly share code, notes, and snippets.

@dkotter
Created January 17, 2012 23:52
Show Gist options
  • Select an option

  • Save dkotter/1629855 to your computer and use it in GitHub Desktop.

Select an option

Save dkotter/1629855 to your computer and use it in GitHub Desktop.
Geocode Custom Fields
add_action( 'save_post', 'dkk_save_latlong' );
function dkk_save_latlong( $post_id ) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// Check if it is our custom post type
if ( 'community-guide' == $_POST['post_type'] ) {
// Check Permissions
if ( !current_user_can( 'edit_post', $post_id ) ) {
return;
}
$street = $_POST['_dkk_address'];
$city_st_zip = $_POST['_dkk_city_state'];
$address = $street .', '. $city_st_zip;
// Send Address to Google to Geocode it
$response = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=false', false, null, null));
$latitude = $response->results[0]->geometry->location->lat;
$longitude = $response->results[0]->geometry->location->lng;
// Update the Custom Field
update_post_meta($post_id, 'location_latitude', $latitude);
update_post_meta($post_id, 'location_longitude', $longitude);
} else {
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment