有什么方法可以缓存WordPress插件的数据吗?我已经准备好使用第三方API对YouTube API V3的访问权限,并且我需要应用缓存以进行优化并将匹配数保持在配额以下。
假设我有这个功能:
function popular_uploads() {
$url = 'https://www.googleapis.com/youtube/v3/search?order=viewCount&part=snippet&channelId='. channel_id(). '&maxResults=5&key={key}&type=video';
$json = file_get_contents($url);
$json_data = json_decode($json, false);
foreach ( $json_data->items as $item ) {
$id = $item->id->videoId;
echo '<iframe id="ytplayer" type="text/html" width="auto" height="auto"
src="//www.youtube.com/embed/' . $id . '?rel=0&showinfo=1"
frameborder="0" allowfullscreen></iframe>';
}
}
我如何在数据库中缓存数据一段时间?我真的是这个过程的新手,我已经查找了它,却找不到解决方法。
非常感谢您对初学者的帮助!
问候。
编辑:
我遵循了简单PHP缓存文章中的所有步骤,唯一的困难是实现以下代码:
<?php
// Some query
$q = mysql_query("SELECT * FROM articles ORDER BY id");
while ($r = mysql_fetch_array($q)) {
echo '<li><a href="view_article.php?id='.$r['id'].'">'.$r['title'].'</a></li>';
}
?>
您应该利用WordPress Transients API来存储临时的可缓存数据。
这使您可以保存一个值,以及该值应缓存的时间量。这是一个如何与您的函数一起工作的示例:
function popular_uploads() {
// Try to retrieve saved data from the cache
$json_data = get_transient('my_unique_identifier');
// If no saved data exists in the cache
if ($json_data === false) {
// Fetch new data from remote URL
$url = 'https://www.googleapis.com/youtube/v3/search?order=viewCount&part=snippet&channelId='. channel_id(). '&maxResults=5&key={key}&type=video';
$json = file_get_contents($url);
$json_data = json_decode($json, false);
// Save the data in the cache, let it live for up to 1 hour (3600 seconds)
set_transient('my_unique_identifier', $json_data, 3600);
}
foreach ( $json_data->items as $item ) {
$id = $item->id->videoId;
echo '<iframe id="ytplayer" type="text/html" width="auto" height="auto"
src="//www.youtube.com/embed/' . $id . '?rel=0&showinfo=1"
frameborder="0" allowfullscreen></iframe>';
}
}
通过使用Transients API,您可以让WordPress决定存储值的最佳方式(在数据库中或某种类型的缓存中)。从文档中:
...暂时性是由缓存插件加速的,而普通的Option则没有。例如,一个memcached插件将使WordPress将瞬态值存储在快速内存中,而不是存储在数据库中。因此,应该使用瞬态来存储任何预期将要到期的数据,或者可以随时到期的数据。暂态也不应被假定为存在于数据库中,因为它们可能根本不存储在数据库中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句