2026年5月20日

2026年5月20日

WordPressのRedisキャッシュを設定する方法(オブジェクトキャッシュ)

はじめに

Redisはインメモリのキーバリューストアで、WordPressのオブジェクトキャッシュとして使うとDBクエリを大幅に削減できます。WP_Object_Cache の永続化バックエンドとして機能し、ページロードあたりのクエリ数を数十〜数百から数個に減らします。

症状・原因

  • ページ表示のたびに同じDBクエリが繰り返される
  • get_optionWP_Query の結果が毎回DBから取得される
  • アクセス増加でMySQLのCPU使用率が高い
  • Transient APIがDBに大量のレコードを蓄積している

解決手順

ステップ1:Redisサーバーのインストール確認

# Ubuntu/Debian
sudo apt install redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server

# 動作確認
redis-cli ping
# PONG が返れば正常

# PHP Redis拡張のインストール
sudo apt install php-redis
sudo systemctl restart php8.2-fpm

ステップ2:wp-config.php でRedisを設定する

// wp-config.php('That's all, stop editing!' の上に追加)

// Redis接続設定
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_DATABASE', 0);           // データベース番号(0-15)
define('WP_REDIS_PREFIX', 'wp_mysite_'); // サイト固有のプレフィックス(複数サイト対応)
define('WP_REDIS_TIMEOUT', 1);           // 接続タイムアウト(秒)
define('WP_REDIS_READ_TIMEOUT', 1);      // 読み取りタイムアウト

// パスワード認証が必要な場合
// define('WP_REDIS_PASSWORD', 'your-redis-password');

// キャッシュしないグループ(デフォルトでも設定済み)
define('WP_REDIS_IGNORED_GROUPS', ['counts', 'plugins', 'themes', 'comment']);

ステップ3:object-cache.php をインストールする

# Redis Object Cacheプラグイン(推奨)
# WordPress管理画面 → プラグイン → 新規追加 → "Redis Object Cache" を検索・インストール

# またはWP-CLIで
wp plugin install redis-cache --activate

# object-cache.phpをwp-contentにコピー(プラグインが自動対応)
wp redis enable
wp redis status
// 手動インストールの場合
// wp-content/object-cache.php が必要
// Redis Object Cacheプラグインのドロップインをコピー

ステップ4:WP_Cache APIを使ってカスタムキャッシュを実装する

// functions.php

// 重いDBクエリをRedisでキャッシュ
function mytheme_get_popular_posts(int $limit = 5): array {
    $cache_key   = 'popular_posts_' . $limit;
    $cache_group = 'mytheme';
    $cached      = wp_cache_get($cache_key, $cache_group);

    if ($cached !== false) {
        return $cached;
    }

    $posts = get_posts([
        'posts_per_page' => $limit,
        'orderby'        => 'comment_count',
        'order'          => 'DESC',
        'post_status'    => 'publish',
    ]);

    // 1時間キャッシュ(Redisなら永続、なければ一時的)
    wp_cache_set($cache_key, $posts, $cache_group, HOUR_IN_SECONDS);

    return $posts;
}

// 投稿更新時にキャッシュを削除
function mytheme_invalidate_post_cache(int $post_id): void {
    wp_cache_delete('popular_posts_5', 'mytheme');
    wp_cache_delete('popular_posts_10', 'mytheme');

    // グループ全体を削除する場合(Redis Object Cache 2.x+対応)
    wp_cache_flush_group('mytheme');
}
add_action('save_post', 'mytheme_invalidate_post_cache');

ステップ5:Redisの動作を確認する

# リアルタイムでRedisのコマンドを監視
redis-cli monitor

# キャッシュに保存されているキーを確認
redis-cli keys "wp_mysite_*" | head -20

# キャッシュヒット率を確認
redis-cli info stats | grep -E "keyspace_hits|keyspace_misses"
# keyspace_hits:1000
# keyspace_misses:50  → ヒット率 95%

# WordPressのクエリ数を確認(WP_DEBUGが必要)
# フッターに追加して確認
// functions.php: キャッシュ統計をフッターに表示(開発環境のみ)
function mytheme_debug_cache_stats(): void {
    if (!WP_DEBUG || !current_user_can('manage_options')) {
        return;
    }

    global $wpdb;
    echo sprintf(
        '<!-- Queries: %d | Cache hits: %s | Time: %.4fs -->',
        $wpdb->num_queries,
        wp_cache_get_stats()['hits'] ?? 'N/A',
        timer_stop(0, 4)
    );
}
add_action('wp_footer', 'mytheme_debug_cache_stats');

注意事項

  • Redisが落ちた場合でもWordPressは動作しますが、全クエリがDBに集中します。Redisの冗長化(Sentinel)を検討してください
  • WP_REDIS_PREFIX はサイトごとに一意にしてください。同一Redisに複数サイトを接続する場合に混在を防ぎます
  • wp_cache_flush() はRedis上の全キャッシュを削除するため、マルチサイトでは他サイトにも影響します

まとめ

Redisはオブジェクトキャッシュの永続化バックエンドとして機能し、wp_cache_get/set の結果をメモリに保持します。WP_REDIS_PREFIX でサイトを分離し、save_post フックでキャッシュを無効化します。redis-cli info stats でヒット率を監視し、チューニングに役立てます。

お気軽にご相談ください

お見積りへ お問い合わせへ