如何在发布帖子时将php代码作为内容传递

时间:2021-05-20 作者:Ravi.

我正在解析JSON数据,并希望在Wordpress帖子中显示它。下面是我想发布的代码。你知道我如何在wp\\u insert\\u post中包含此内容吗。

$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]

1 个回复
SO网友:anton

我将给你一个简单的例子,你可以根据自己的目的修改它

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.195Showers, 所以我想它工作得很好;)