我需要根据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;
}