如何在 WordPress 插件的 SQL 数据库中缓存第三方 API 访问

How to cache third party API access in SQL database for a WordPress plugin

有什么方法可以缓存 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>';
        }
}

我如何在数据库中缓存数据一段时间?我对这个过程真的很陌生,我已经查过了但找不到解决方法。

非常感谢您帮助初学者!

此致。

编辑:

我已按照 Simple PHP caching 文章中的所有步骤进行操作,唯一的困难是实现以下代码:

<?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 决定存储值的最佳方式(在数据库中,或在某种缓存中)。 From the documentation:

...Transients are inherently sped up by caching plugins, where normal Options are not. A memcached plugin, for example, would make WordPress store transient values in fast memory instead of in the database. For this reason, transients should be used to store any data that is expected to expire, or which can expire at any time. Transients should also never be assumed to be in the database, since they may not be stored there at all.