Transients APIで外部APIを30分キャッシュ
概要
外部APIの結果をget_transient/set_transientで一時キャッシュ。アクセス集中時でも安定し、体感速度が改善。DBやオブジェクトキャッシュに進む前の第一歩。
PHP
function demo_fetch_data() {
if ($cache = get_transient('demo_api_cache')) return $cache;
$res = wp_remote_get('https://jsonplaceholder.typicode.com/todos/1', ['timeout' => 8]);
if (is_wp_error($res)) return ['error' => $res->get_error_message()];
$json = json_decode(wp_remote_retrieve_body($res), true);
set_transient('demo_api_cache', $json, 30 * MINUTE_IN_SECONDS);
return $json;
}解説
・「取得→キャッシュ→返す」の3行セットを関数化
・失敗時は直にエラー文字列を返さない(配列に包む等)
・運用ではキーにバージョンを付けて破棄も容易に


