I asked a question on "https://stackoverflow.com/questions/70013277/getting-json-data-results-in-warning-htmlspecialchars-expects-parameter-1-to" that basically was looking for a way to get JSON data from a url and save it as a custom field.
My code so far:
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 );
If The JSON data looks like this:
{
"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"
},
How do I save the "url" to a custom field called "link_url"? I tried using update_field('link_url', $data->url);
and nothing happened.
2
Answers
I was able to get this to work:
Use the field key instead of the field name.