Geocoding custom user meta in WordPress

I’m using User Front End Pro to provide a front end registration form. One line of that is for an address, and I want to use that to display a map of all users with Geo Mashup.

I have a custom field that saves to user meta called geocode_address, I need to then geocode it and output it to two separate fields Latitude and Longitude. I found this for geocoding custom post data, and have tried to amend it for user meta, but it is not working, and causes the registration to hang. What have I done wrong?

Read More
function geocode_address($user_id)
{
$custom_fields = get_user_meta();
if(isset($custom_fields["geocode_address"]) && !empty($custom_fields["geocode_address"][0]))
{
    $resp = wp_remote_get( "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($custom_fields["geocode_address"][0])."&sensor=false" );
    if ( 200 == $resp['response']['code'] ) {
        $body = $resp['body'];
        $data = json_decode($body);
        if($data->status=="OK"){
            $latitude = $data->results[0]->geometry->location->lat;
            $longitude = $data->results[0]->geometry->location->lng;
            update_user_meta($user_id, "latitude", $latitude);
            update_user_meta($user_id, "longitude", $longitude);
        }
    }
}
}
add_action('update_user_meta', 'geocode_address');

As a side note, Geomashup has a function to geocode a custom field, but when I enter “geocode address” it doesn’t seem to work…

Related posts

Leave a Reply

1 comment

  1. The action update_user_meta takes more arguments and the first one is not the User ID:

    add_action('update_user_meta', 'geocode_address', 10, 4 );
    
    function geocode_address( $meta_id, $user_id, $meta_key, $meta_value )
    {
        if( 'geocode_address' == $meta_key )
        {
            var_dump( $meta_value );
            die();
        }
    }
    

    Then, you’re using get_user_meta() wrong, we need to pass at least the User ID: get_user_meta($user_id, $key = '', $single = false);. But I suspect it’s not needed in your case.

    As for the Geocode API, it returned a correct response when I tested with a random spanish address:

    $address = "gran via, madrid";
    $resp = wp_remote_get( "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($address)."&sensor=false" );