我将给你一个简单的例子,你可以根据自己的目的修改它
save_weather_field
此功能将添加/更新/删除任何帖子元(如果您决定添加更多天气字段)。我们将在下面的后期保存操作中使用它。
function save_weather_field($post_id, $key, $value)
{
//new value we pass in this function
$new_meta_value = ( isset( $value ) ? sanitize_text_field( $value ) : false );
//old value from database
$meta_value = get_post_meta( $post_id, $key, true );
//if new value exists and old value not - we add post meta
if ( $new_meta_value && false == $meta_value )
add_post_meta( $post_id, $key, $new_meta_value, true );
//if old value exists but we have new value - update post meta
elseif ( $new_meta_value && $new_meta_value != $meta_value )
update_post_meta( $post_id, $key, $new_meta_value );
//if old value exists but new value is empty - delete post meta
elseif ( false == $new_meta_value && $meta_value )
delete_post_meta( $post_id, $key, $meta_value );
}
weather_metadata_save此函数在post保存时触发(“post”post type)。
function weather_metadata_save($post_id, $post, $update){
//return if user don\'t have permissions to edit post
if(!current_user_can("edit_post", $post_id))
return $post_id;
//return if post submitted with XHR
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
return $post_id;
//your code
$url = "http://metaweather.com/api/location/2379574";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
$weather_sate=$json_data[\'consolidated_weather\'][0][\'weather_state_name\'];
$temperature=$json_data[\'consolidated_weather\'][0][\'the_temp\'];
/save weather sate if it exists
if( !empty($weather_sate) ):
save_weather_field($post_id, \'weather-sate\', $weather_sate);
endif;
//save temperature if exists
if( !empty($temperature) ):
save_weather_field($post_id, \'temperature\', $temperature);
endif;
}
add_action("save_post_post", "weather_metadata_save", 10, 3);
我用过
temperature
作为温度和
weather-state
用于天气状态。因此,您可以将其作为任何其他post meta获取:
$temperature = get_post_meta($post->ID, \'temperature\', true);
$weather_state = get_post_meta($post->ID, \'weather-state\', true);
另外,我在本地主机上尝试了这段代码
27.195
和
Showers
, 所以我想它工作得很好;)