2026年5月21日
2026年5月21日
WordPressキャッシュプラグインの設定方法【WP Rocket・LiteSpeed・W3 Total Cache】
はじめに
WordPressサイトを高速化する最も効果的な方法のひとつが「キャッシュ」の活用です。キャッシュを正しく設定することでサーバーの処理負荷を軽減し、ページ表示時間を大幅に短縮できます。
症状・原因
- 毎回のページアクセスでPHPとDBの処理が走り、サーバー負荷が高い
- 同じページを複数のユーザーが閲覧する際に、毎回同じコンテンツを生成している
- Time to First Byte(TTFB)が遅い(200ms以上)
解決手順
ステップ1:プラグインなしでTransient APIキャッシュを実装する
// Transient APIでデータベースクエリをキャッシュ
function get_cached_popular_posts(int $limit = 5): array {
$cache_key = "popular_posts_{$limit}";
$cached = get_transient($cache_key);
if ($cached !== false) {
return $cached; // キャッシュヒット
}
// 重いクエリを実行
$posts = get_posts([
'numberposts' => $limit,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'post_status' => 'publish',
]);
// 1時間キャッシュ
set_transient($cache_key, $posts, HOUR_IN_SECONDS);
return $posts;
}
// 投稿更新時にキャッシュをクリア
add_action('save_post', function(int $post_id): void {
if (wp_is_post_revision($post_id)) return;
// 関連するTransientを削除
delete_transient('popular_posts_5');
delete_transient('popular_posts_10');
// WP Object Cacheもフラッシュ
wp_cache_delete($post_id, 'posts');
wp_cache_delete($post_id, 'post_meta');
});
ステップ2:Object Cacheを導入する(Redis/Memcached)
# Redisをインストール
sudo apt install redis-server php-redis
sudo systemctl enable --now redis-server
# Redis接続確認
redis-cli ping # PONG が返ればOK
# wp-config.php に追加
// wp-config.php: Redis Object Cache設定
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_DATABASE', 0);
define('WP_REDIS_TIMEOUT', 1);
define('WP_REDIS_READ_TIMEOUT', 1);
// Redis Object Cache プラグインをインストール後
// WP-CLIで有効化
// wp redis enable
// カスタムObject Cache操作
function cache_heavy_calculation(string $key, callable $callback, int $ttl = 3600): mixed {
$cached = wp_cache_get($key, 'my_plugin');
if ($cached !== false) {
return $cached;
}
$result = $callback();
wp_cache_set($key, $result, 'my_plugin', $ttl);
return $result;
}
// 使用例
$data = cache_heavy_calculation(
'site_stats',
fn() => calculate_site_statistics(),
HOUR_IN_SECONDS
);
ステップ3:ページキャッシュを実装する
// シンプルなページキャッシュ実装
class Simple_Page_Cache {
private string $cache_dir;
public function __construct() {
$this->cache_dir = WP_CONTENT_DIR . '/cache/simple-page-cache/';
}
public function get_cache_file(): string {
$uri = $_SERVER['REQUEST_URI'] ?? '/';
$hash = md5($uri);
return $this->cache_dir . $hash . '.html';
}
public function serve_if_cached(): void {
if (is_user_logged_in()) return;
$file = $this->get_cache_file();
if (file_exists($file) && (time() - filemtime($file)) < 3600) {
header('X-Cache: HIT');
readfile($file);
exit;
}
}
public function save_cache(string $html): string {
if (!is_user_logged_in() && !is_admin()) {
wp_mkdir_p($this->cache_dir);
file_put_contents($this->get_cache_file(), $html);
}
return $html;
}
}
$cache = new Simple_Page_Cache();
$cache->serve_if_cached();
add_filter('final_output', [$cache, 'save_cache']);
ステップ4:W3 Total Cacheの最適設定(無料)
// functions.php: W3TCのキャッシュを特定ページで無効化
add_filter('w3tc_is_page_cacheable', function(bool $cacheable): bool {
// カートページ・マイアカウントページはキャッシュしない
if (function_exists('is_cart') && is_cart()) return false;
if (function_exists('is_account_page') && is_account_page()) return false;
return $cacheable;
});
// W3TCのminifyから特定スクリプトを除外
add_filter('w3tc_minify_js_do_tag_minification', function(bool $do, array $tag): bool {
// Google Tag Manager は除外
if (str_contains($tag['src'] ?? '', 'googletagmanager')) {
return false;
}
return $do;
}, 10, 2);
ステップ5:キャッシュのデバッグと確認
# キャッシュが効いているか確認
curl -I https://example.com/ | grep -E "(x-cache|age|cf-cache)"
# Transientをリスト表示(WP-CLI)
wp transient list --human-readable
# 期限切れTransientを削除
wp transient delete --expired
# Object Cache統計(Redisの場合)
wp redis status
wp cache stats
# ページキャッシュファイル確認
ls -lh wp-content/cache/ | head -20
du -sh wp-content/cache/
注意事項
- WooCommerce: カート・チェックアウト・マイアカウントページは必ずキャッシュから除外してください
- ログインユーザー: ログイン中のユーザーにはキャッシュを提供しないよう設定してください
- プラグイン競合: 複数のキャッシュプラグインを同時に使用しないでください
- HTTPS: 混在コンテンツを防ぐため、HTTPとHTTPSのキャッシュは分けて管理してください
まとめ
キャッシュの種類は「Transient API(DB結果)・Object Cache(Redis)・ページキャッシュ(HTML全体)」の3層です。用途に合わせて組み合わせることで最大限の効果が得られます。LiteSpeed Cacheを使用するLiteSpeedサーバーやNginx Fastcgicacheを使用するNginxサーバーはサーバーレベルキャッシュが最も効果的です。関連記事:CDN設定方法