0

I have a custom post type for clinics which has 3 fields; a textarea for the address of a the clinic and two textboxes for latitude and longitude. I want the user to enter the address in the textarea and then when they hit publish I need to hook in, geocode the address and populate the latitude and longitude fields to be stored in the database. If this is successful then when they come to edit the clinic the latitude and longitude fields will be populated. I have the following code but it doesn't seem to work:

function geocode_clinic() 
{
if($_POST['post_type']=='clinics') 
{
    $address = urlencode($_POST['fields']['field_52ea48969a9f2']);

    // geocode the address
    $location = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".str_replace(" ", "+", $address)."&sensor=false"));

    if ($data->status=="OK") {          
        $lat = $data->results[0]->geometry->location->lat;
        $lng = $data->results[0]->geometry->location->lng;
    } else {
        $lat = $lng = '';
    }

    $_POST['fields']['field_52ea4b66b382f'] = $lat;
    $_POST['fields']['field_52ea4bccb3830'] = $lng;
}
}
add_action('save_post', 'geocode_clinic');
2

save_post is much too late to modify the $_POST data itself and hope to have it populate to the post save actions (and modifying $_POST is usually not necessary anyway). The post has been saved at that point. Just check the source.

What you should probably be doing is saving your data to the database explicitly using update_post_meta.

Something like this:

function geocode_clinic($post_id ) 
{
if($_POST['post_type']=='clinics') 
{
    $address = urlencode($_POST['fields']['field_52ea48969a9f2']);

    // geocode the address
    $location = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".str_replace(" ", "+", $address)."&sensor=false"));

    if ($data->status=="OK") {          
        $lat = $data->results[0]->geometry->location->lat;
        $lng = $data->results[0]->geometry->location->lng;
    } else {
        $lat = $lng = '';
    }

    update_post_meta($post_id,'field_52ea4b66b382f',$lat);
    update_post_meta($post_id,'field_52ea4bccb3830',$lng);
}
}
add_action('save_post', 'geocode_clinic');

I am not sure those are the key names you want but that is the idea.

  • There are WordPress HTTP APIs you can use instead of file_get_contents – JMau Jan 30 '14 at 17:10
  • @JMau : yes there are. That part of the code comes from the OP and doesn't effect the answer. I didn't alter it, but feel free to make the change if you'd like. – s_ha_dum Jan 30 '14 at 17:28
  • sorry I don't get it. – JMau Jan 31 '14 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.