Home > Software design >  Getting JSON data results in warning: htmlspecialchars() expects parameter 1 to be string, array giv
Getting JSON data results in warning: htmlspecialchars() expects parameter 1 to be string, array giv

Time:11-20

I paid someone to make a plugin for my website 5 years ago and now I'm trying to get it to work again. I have no knowledge of how JSON works so this is my first experimenting with it. Basically my plugin would use the Iframely API to get a summary of an article and save the data to a custom field from a URL in the editor.

The code I have in question in my function.php is this:

function post_extra_save( $post_id, $post){
global $pagenow;
if ($pagenow == 'post.php') {
    if ( has_post_format('link', $post_id)) {
        $url = get_post_field('post_content', $post_id);
        $request_url = 'https://iframe.ly/api/iframely?url='. urlencode($url) .'&api_key='.get_field_object('api_key', 'option')['value'];
        $response = wp_remote_get( esc_url_raw( $request_url ) );
        $api_response = json_decode( wp_remote_retrieve_body( $response ), true );
        update_field('field_61942d74195e7', $api_response);
    }
}
}
add_action( 'save_post', 'post_extra_save', 10, 2 );

What it does is send a URL plus the API key to Iframely API, returns the JSON and save the raw output to a custom field.

When I save the post, I get this error message:

Warning: htmlspecialchars() expects parameter 1 to be string, array given in /wp-includes/formatting.php on line 4529

Any idea what this means?

CodePudding user response:

Found my problem. What I got it to work was it gets the URL from the post content, encode it from the raw JSON and decode it.

$request = wp_remote_get( 'https://iframe.ly/api/iframely?url='. urlencode($url) .'&api_key='.get_field_object('api_key', 'option')['value'] );
$data_raw = json_encode( wp_remote_retrieve_body( $request ));
$data = json_decode($data_raw);
  • Related