【问题标题】:Update meta_value in wp_postmeta from an API response从 API 响应更新 wp_postmeta 中的 meta_value
【发布时间】:2021-04-12 02:06:44
【问题描述】:

我正在使用 wp_remote_get 方法进行 API 调用,以从外部源(不是 WP 站点)获取数据。 API 调用正在工作,我得到了我想要的响应,这只是一个数字。现在我想将此数字(响应)存储为 wp_postmeta 中的 meta_value,并带有以下 meta_key(donation_amount)和特定的 post_id。数据库表已经存在。到目前为止,我所拥有的是 API 调用和响应。我已经尝试过 wp_update_post 但也许我做错了什么或者可能不是正确的方法。任何帮助将不胜感激。

$url = 'https://developer.mozilla.org/en-US/docs/Web/API/URL_API'; // Not the real url

$response = wp_remote_get( $url );

if( is_wp_error( $response ) ) {
    return false;
} else {
    $api_response = json_decode( wp_remote_retrieve_body( $response ), true );
}


echo $api_response ['theNumber'];

【问题讨论】:

    标签: wordpress api


    【解决方案1】:

    使用 WPupdate_post_meta 函数。检查下面的代码。

    $url = 'https://developer.mozilla.org/en-US/docs/Web/API/URL_API'; // Not the real url
    
    $response = wp_remote_get( $url );
    
    if( is_wp_error( $response ) ) {
        return false;
    } else {
        $api_response = json_decode( wp_remote_retrieve_body( $response ), true );
    }
    
    $donation_amount = $api_response['theNumber'];
    

    $post_id 替换为您的帖子 ID。

    update_post_meta( $post_id, 'donation_amount', $donation_amount );
    

    【讨论】:

    • 我的回答对你有帮助吗?
    • 再次感谢您!它工作得很好。我忘记了 $donation_amount = $api_response ['theNumber'];
    • 欢迎...很高兴为您提供帮助。如果这个答案对你有帮助,那么你可以accept 答案,如果你喜欢/想要你也可以upvote 答案,谢谢。
    • 我当然接受了你的回答,并且我投票赞成,也许你看不到它,因为我没有获得适当的投票特权。再次感谢您@Bhautik
    猜你喜欢
    • 2020-04-21
    • 2017-08-07
    • 2017-06-21
    • 2017-03-05
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    相关资源
    最近更新 更多