Created
October 25, 2018 10:05
-
-
Save celticwebdesign/49c52b22f7eaee137b2f9d3a07cd9cf1 to your computer and use it in GitHub Desktop.
Geocoding a postcode using WordPress post meta.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$prev_location = get_post_meta($post->ID, '_cottages_custom_postal_code', true ); | |
$lat = get_post_meta($post->ID, '_cottages_custom_location_latitude', true ); | |
$lng = get_post_meta($post->ID, '_cottages_custom_location_longitude', true ); | |
if ( | |
( | |
$cottages_meta['_cottages_custom_postal_code'] != '' && | |
$prev_location != $cottages_meta['_cottages_custom_postal_code'] | |
) || | |
$lat == '' || | |
$lng == '' | |
){ | |
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($cottages_meta['_cottages_custom_postal_code']) . "&key=XXX&sensor=false"; | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
$data = curl_exec($ch); | |
curl_close($ch); | |
$data = json_decode($data); | |
if( $data ){ | |
if( is_array( $data->results )){ | |
$lat_lng = $data->results[0]->geometry->location; | |
$cottages_meta['_cottages_custom_location_latitude'] = $lat_lng->lat; | |
$cottages_meta['_cottages_custom_location_longitude'] = $lat_lng->lng; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment