Support » Plugin: Import any XML or CSV File to WordPress » Geocode automatically from address field

  • Resolved greencode


    I’m struggling to get the following function to work. Just wondering if anybody has had any success or could help with this.

    From my CSV import I am trying to automatically get the Longitude and Latitude based on the address field and add it to the relevant custom fields before saving the post.

    function my_save_custom_field_address( $post_id, $xml_data, $is_update ) {
        $address_custom_field = 'field_5c6d73c87ba23'; // The custom field you imported the address into
        $api_key = 'mygoogleAPIkeyhere'; // Your Google Maps Geocoding API Key
        $lat_cf = 'field_5c6d75323cc61'; // The custom field you want the latitude imported into
        $lng_cf = 'field_5c6d75273cc60'; // The custom field you want the longitude imported into
        if ( $address = get_post_meta( $post_id, $address_custom_field, true ) ) {
            $google_url = '' . rawurlencode( $address ) . '&key=' . $api_key;
            $curl = curl_init();
            curl_setopt( $curl, CURLOPT_URL, $google_url );
            curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
            $json = curl_exec( $curl );
            curl_close( $curl );
            if ( !empty( $json ) ) {
                $details = json_decode( $json, true );
                $lat = $details['results'][0]['geometry']['location']['lat'];
                $lng = $details['results'][0]['geometry']['location']['lng'];
                update_post_meta( $post_id, $lat_cf, $lat );
                update_post_meta( $post_id, $lng_cf, $lng );
    add_action( 'pmxi_saved_post', 'my_save_custom_field_address', 10, 3 );

    I have tried changing the custom field names (as these are Advanced Custom Fields) but still no content is added to the fields. I have tested my API key is working and it appears to be so really unsure why this won’t work.

    This is based on this post

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Geocode automatically from address field’ is closed to new replies.