繁体   English   中英

使用 WordPress 缓存 Instagram 提要

[英]Using WordPress to cache Instagram feed

我的网站上有一个 Instagram 提要:

$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 } ?>

这运行良好,但我最近发现 Instagram 限制为每小时 200 个请求。

我的问题是 - 我可以缓存这些结果吗?

我试过使用set_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';

} 

?>

但似乎没有设置瞬态,它每次都在调用。

看看你正在使用的这段代码。

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

首先,您必须将数据保存在变量 cached_result 中,然后对其进行设置。 您正在调用 get_transient 的第一行代码,但由于未设置该值,因此瞬态键上没有值。

谢谢!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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