WordPress plugin call to external API

Date: 2020-02-06

https://wordpress.stackexchange.com/a/266728

<?php
/*
    Template Name: My Api Page
*/
function get_from_api()
{
    $key = 'my_custom_api_data2';
	$cache_seconds = 60;
	
    $cached = \wp_cache_get($key);
    if (!empty($cached)) {
        return $cached;
    }
    $response = \wp_remote_get('https://jsonplaceholder.typicode.com/users/');
	if ( is_array( $response ) && ! is_wp_error( $response ) ) {
    	$headers = $response['headers']; // array of http header lines
    	$body = $response['body']; // use the content
		$data = json_decode($body);
		\wp_cache_set($key, $data, '', $cache_seconds);
        return $data;
	}
	return [];
}

try
{
	$users = get_from_api();
    foreach ($users as $key => $user) {
        echo "{$user->name}<br>";
    }
} catch(\Throwable $th) {
	echo $th->message;
}
33630cookie-checkWordPress plugin call to external API