php - 使用 WordPress 缓存 Instagram 提要
问题描述
我的网站上有一个 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 的第一行代码,但由于未设置值,因此瞬态键上没有值。
谢谢!!
推荐阅读
- postgresql - 从日期开始计算 Postgress 中给定月份的周范围
- python - 在列表 python 上找到一个以上的平均值
- python - 如何按下硒弹出打印的“保存”按钮?
- powershell - Powershell 将 DatabaseCollection 分配给变量
- flutter - 使用 Clean Architecture 和 TDD Flutter Google OAuth
- github - 如何将包直接从 github 添加到 Julia?
- python - 如何使用 Beautifulsoup 提取没有标签的 HTML 文本?
- machine-learning - 基于协作过滤器的推荐系统的交叉验证
- c++ - 未调用模板方法重载
- amazon-web-services - 在 Quicksight 计算字段中,如果“午餐”=“午餐”,我如何为每个“天”的“用户名”字段执行 distinct_countif