简体   繁体   中英

Using WordPress to cache Instagram feed

I have an Instagram feed on my website:

$instagram_user_id = 'MY USER ID';
$instagram_access_token = 'MY ACCESS TOKEN';

<?php

function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

$result = fetchData("https://api.instagram.com/v1/users/$instagram_user_id/media/recent/?access_token=$instagram_access_token&count=9");
$result = json_decode($result); ?>

<?php foreach ($result->data as $insta) { 

echo '<a target="blank" href="'.$insta->link.'">';

$img = $insta->images->low_resolution->url;
?>

<div style="background-image: url('<?php echo $img; ?>'); background-size: cover; background-position: center center;"></div></a>

<?php } ?>

This is working well but I recently discovered that Instagram limits to 200 requests per hour.

My question is - can I cache these results?

I have tried using set_transient but with no luck.

Edit: this is how I am trying to use transient:

<?php

$cached_result = get_transient('transient');

//if transient is not set
if(empty($cached_result)) { 

function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

$result = fetchData("https://api.instagram.com/v1/users/$instagram_user_id/media/recent/?access_token=$instagram_access_token&count=9");
$result = json_decode($result);

//set the transient
set_transient('transient', $cached_result, 60*60*6);

}
//tell me if transient is set
if(!empty($cached_result)) {

echo 'full';

} 

?>

But it doesn't seem the transient is set, it's calling each time.

ULook at this code you are using.

set_transient('transient', $cached_result, 60*60*6);

First you have to hold the data in the variable cached_result then set it. The first line of code you are calling get_transient but there is no value on the transient key just because the value is not set.

Thanks!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM