任何与使用Google Places API有关的内容都将脱离主题,但最好从这里开始the developer docs.
然而,如何在WordPress中和API数据交互肯定是一个主题。我建议使用包装器函数定期缓存结果:
/**
* Get places data for a post.
*
* @param int|WP_Post $post Optional, defaults to current post.
* @return mixed
*/
function wpse_187541_google_places_data( $post = null ) {
if ( ! $post = get_post( $post ) )
return;
if ( ! $place_id = get_post_meta( $post->ID, \'place_id\', true ) )
return; // No place ID configured for this post
if ( $data = get_post_meta( $post->ID, \'place_data\', true ) ) {
if ( $data->timeout <= current_time( \'timestamp\' ) )
$data = null; // Void the cache if it\'s old
}
if ( ! $data ) {
$args = http_build_query(
array(
\'key\' => \'\', // API key
\'placeid\' => $place_id,
)
);
$http = wp_remote_get( "https://maps.googleapis.com/maps/api/place/details/json?$args" );
if ( $body = wp_remote_retrieve_body( $http ) ) {
if ( $data =@ json_decode( $body ) )
$data->timeout = current_time( \'timestamp\' ) + HOUR_IN_SECONDS; // Cache data for 1 hour
}
if ( $data ) {
update_post_meta( $post->ID, \'place_data\', $data );
} else {
// Something went wrong.
// Perhaps check HTTP response and decide cause of problem.
// Don\'t want to keep hitting the API on every call if the error is permanent (i.e. invalid place id etc.)
}
}
return $data;
}