自动更新帖子的LAT和LNG会产生零星的结果

时间:2017-11-08 作者:Jordan Carter

我需要根据CSV导入输入的地址,自动更新帖子的lat和lng元字段。出于某种原因,当我运行处理此问题的插件时,失败更新的数量有时会发生变化。有什么见解可以解释为什么会这样?下面是处理更新的函数。它依靠谷歌地图为我提供JSON数据,我对这些数据进行解码。

function jwd_update_all_stores_action()
{

 echo \'<h3>Results Log:</h3>\';


$posts = get_posts( array(\'post_type\' => \'wpsl_stores\', \'numberposts\' => -1 ) );

foreach ( $posts as $post ):

  //$my_post->post_content = \'This is the updated content.\';

  $id = $post->ID;
  $long = get_post_meta($id, \'wpsl_lng\', true);
  $lat = get_post_meta($id, \'wpsl_lat\', true);

  $title = get_the_title($id);
  $street = get_post_meta($id, \'wpsl_address\', true);
  $city = get_post_meta($id, \'wpsl_city\', true);
  $state = get_post_meta($id, \'wpsl_state\', true);

  $address = $street .\', \'. $city .\', \'. $state;
  $prepAddr = str_replace(\' \',\'+\',$address);
  $geocode=file_get_contents(\'https://maps.google.com/maps/api/geocode/json?address=\'.$prepAddr.\'&sensor=false\');
  $output = false;

  if ($geocode){
    $output= json_decode($geocode);
  }

  if ($output && $output->results)
  {
    $new_lat = $output->results[0]->geometry->location->lat;
    $new_long = $output->results[0]->geometry->location->lng;

    update_post_meta( $id, \'wpsl_lng\', $new_long );
    update_post_meta( $id, \'wpsl_lat\', $new_lat );

    echo $title . \' (\'.$street.\') updated successfully <br>\';
  }
  else
  {
    echo \'ERROR: \' .$title . \' (\'.$street.\') did not update successfully! Please edit this manually. <br>\';
  }

endforeach;
}

1 个回复
SO网友:Jordan Carter

原来这是一个没有提供地理代码API的问题!我需要改变

$geocode=file_get_contents(\'https://maps.google.com/maps/api/geocode/json?address=\'.$prepAddr.\'&sensor=false\');

$geocode = file_get_contents(\'https://maps.google.com/maps/api/geocode/json?address=\'.$prepAddr.\'&key=\'.$api_key);
换句话说,该URL中需要具有API键的键参数。我还删除了传感器参数,因为这似乎不需要。

结束