我正在尝试将Google Places API与WordPress结合使用。我试图创建一个函数,从中获取API数据并将其存储为自定义字段。
我找到了一个similar answer, 但它只处理缓存。
This answer 有帮助,但不详细。
我想使用wp\\u remote\\u get()来检索JSON数据。
我的目标是在single中使用get\\u post\\u meta()访问任何自定义字段数据。php
我正在尝试将Google Places API与WordPress结合使用。我试图创建一个函数,从中获取API数据并将其存储为自定义字段。
我找到了一个similar answer, 但它只处理缓存。
This answer 有帮助,但不详细。
我想使用wp\\u remote\\u get()来检索JSON数据。
我的目标是在single中使用get\\u post\\u meta()访问任何自定义字段数据。php
我了解了如何将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 );
事实上,我在发帖方面没有问题。我需要在php中使用REST API创建帖子file_get_contents.这是我的代码:json_decode( file_get_contents( \"http://my-site.com/wp-json/wp/v2/posts\", false, stream_context_create( array(