如何将单个 JSON 数据保存到自定义字段?
Posted
技术标签:
【中文标题】如何将单个 JSON 数据保存到自定义字段?【英文标题】:How to save individual JSON data to a custom field? 【发布时间】:2021-12-31 02:19:44 【问题描述】:我在“https://***.com/questions/70013277/getting-json-data-results-in-warning-htmlspecialchars-expects-parameter-1-to”上问了一个问题,基本上是在寻找一种方法从 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);
,但没有任何反应。
【问题讨论】:
【参考方案1】:我能够让它工作:
// 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);
【讨论】:
【参考方案2】:使用字段键代替字段名。
$field = get_field_object('link_url');
update_field($field["key"],$data->url);
【讨论】:
那行不通。以上是关于如何将单个 JSON 数据保存到自定义字段?的主要内容,如果未能解决你的问题,请参考以下文章
xml 将Yotpo Stars(每个产品和网站评论)保存到自定义字段
xml 将Yotpo Stars(每个产品和网站评论)保存到自定义字段