如何将单个 JSON 数据保存到自定义字段?

How to save individual JSON data to a custom field?

我在“ url 获取 JSON 数据并将其保存为自定义字段。

到目前为止我的代码:

function post_extra_save( $post_id, $post){
global $pagenow;
// Work if on the editor
if ($pagenow == 'post.php') {
    // if post is a link in post format
    if ( has_post_format('link', $post_id)) {
        // get URL from post_content
        $url = get_post_field('post_content', $post_id);
        // fetch JSON data from Iframely
        $request = wp_remote_get( 'https://iframe.ly/api/iframely?url='. urlencode($url) .'&api_key='.get_field_object('api_key', 'option')['value'] );
        // encode the raw data
        $data_raw = json_encode( wp_remote_retrieve_body( $request ));
        // decode the data
        $data = json_decode($data_raw);
    }
}
}
add_action( 'save_post', 'post_extra_save', 10, 2 );

如果 JSON 数据如下所示:

{
"url": "https://www.technologyreview.com/2021/11/20/1039076/facebook-google-disinformation-clickbait/",
"meta": {
    "description": "The tech giants are paying millions of dollars to the operators of clickbait pages, bankrolling the deterioration of information ecosystems around the world.",
    "title": "How Facebook and Google fund global misinformation",
    "medium": "article",
    "amphtml": "https://www.technologyreview.com/2021/11/20/1039076/facebook-google-disinformation-clickbait/amp/",
    "date": "2021-11-20T17:50:00.000Z",
    "canonical": "https://www.technologyreview.com/2021/11/20/1039076/facebook-google-disinformation-clickbait/",
    "category": "Silicon Valley",
    "site": "MIT Technology Review",
    "author": "Karen Hao"
},

如何将“url”保存到名为“link_url”的自定义字段?我尝试使用 update_field('link_url', $data->url); 但没有任何反应。

使用字段键代替字段名。

$field = get_field_object('link_url');
update_field($field["key"],$data->url);

我能够让它工作:

// get URL from post_content
$url = get_post_field('post_content', $post_id);
// fetch JSON data from Iframely
$request = wp_remote_get( 'https://iframe.ly/api/iframely?url='. urlencode($url) .'&api_key='.get_field_object('api_key', 'option')['value'] );
// encode the raw data
$data_raw = json_encode( wp_remote_retrieve_body( $request ));
// decode the data
$data = json_decode($data_raw);
// decode it again
$data2 = json_decode($data);
// save the $data outut
update_field('raw', $data);
// save the url from $data2
update_field('link_url', $data2->url);