我了解了如何将JSON数据存储到自定义字段中。我完全忘记了使用add\\u操作。
下面是我在函数中添加的答案。php。
您必须添加自定义字段place\\u id及其值,然后单击“发布”或“更新”以填充其他字段。
function 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\' => \'AIzaSyCarm54WzOXFhXqmEU3rkUorDoa8b3Nzog\', // 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
$place_address = $data->result->formatted_address;
$place_lat = $data->result->geometry->location->lat;
$place_long = $data->result->geometry->location->lng;
$place_phone = \'000-000-010\';
update_post_meta( $post->ID, \'place_address\', $place_address );
update_post_meta( $post->ID, \'place_lat\', $place_lat );
update_post_meta( $post->ID, \'place_long\', $place_long );
update_post_meta( $post->ID, \'place_phone\', $place_phone );
}
if ( $data ) {
update_post_meta( $post->ID, \'place_data\', $data );
} else {
echo \'api error\';
}
}
return $data;
}
add_action( \'save_post\', \'google_places_data\', 10, 4 );