首页 > 解决方案 > 使用 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';

} 

?>

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

标签: phpwordpressinstagram

解决方案


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

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

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

谢谢!!


推荐阅读