2026年5月20日

2026年5月20日

WordPressのCSSを最小化(Minify)する方法

はじめに

CSSの最小化(Minify)はコメント・空白・改行を除去してファイルサイズを削減します。さらに不要なCSSファイルの読み込みを止め、クリティカルCSSをインラインに配置することで、レンダリングブロックを解消しページの表示速度を改善できます。

症状・原因

  • PageSpeed Insightsで「レンダリングブロックリソースの除外」を指摘される
  • 使っていないプラグインのCSSが毎ページ読み込まれている
  • CSSファイルが複数に分割されHTTPリクエストが多い
  • ファーストビューに関係ないCSSが優先的に読み込まれている

解決手順

ステップ1:不要なCSSを読み込まないようにする

// functions.php

// 特定ページ以外でプラグインのCSSを無効化
function mytheme_dequeue_unused_styles(): void {
    // コンタクトフォーム7のCSSをフォームがあるページ以外で無効化
    if (!is_page('contact')) {
        wp_dequeue_style('contact-form-7');
        wp_deregister_style('contact-form-7');
    }

    // WooCommerceのCSSをショップ関連ページ以外で無効化
    if (!is_woocommerce() && !is_cart() && !is_checkout()) {
        wp_dequeue_style('woocommerce-general');
        wp_dequeue_style('woocommerce-smallscreen');
        wp_dequeue_style('woocommerce-layout');
    }

    // ブロックエディターのギャラリーCSSをフロントエンドで無効化
    wp_dequeue_style('wp-block-library');
    wp_dequeue_style('wp-block-library-theme');
    wp_dequeue_style('classic-theme-styles');
    wp_dequeue_style('global-styles');
}
add_action('wp_enqueue_scripts', 'mytheme_dequeue_unused_styles', 100);

ステップ2:CSSをインライン化してレンダリングブロックを解消する

// functions.php

// 小さいCSSファイルをインラインで出力してHTTPリクエストを削減
function mytheme_inline_critical_css(): void {
    // クリティカルCSS(ファーストビューに必要なスタイル)をインラインに
    $critical_css_file = get_template_directory() . '/assets/css/critical.css';

    if (!file_exists($critical_css_file)) {
        return;
    }

    $css = file_get_contents($critical_css_file);

    // コメントと空白を除去(簡易Minify)
    $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css); // コメント削除
    $css = preg_replace('/\s+/', ' ', $css);                          // 連続空白を1つに
    $css = str_replace([' {', '{ ', ' }', '} ', ': ', ' ;'], ['{', '{', '}', '}', ':', ';'], $css);

    echo '<style id="critical-css">' . $css . '</style>' . "\n";
}
add_action('wp_head', 'mytheme_inline_critical_css', 1); // 最優先で出力

// 残りのCSSをレンダリングブロックしないよう非同期読み込み
function mytheme_preload_main_css(string $html, string $handle): string {
    if ($handle !== 'mytheme-main') {
        return $html;
    }

    // preload → onload で非同期読み込み
    $html = str_replace("rel='stylesheet'", "rel='preload' as='style' onload=\"this.onload=null;this.rel='stylesheet'\"", $html);
    $html .= '<noscript>' . str_replace('preload', 'stylesheet', $html) . '</noscript>';

    return $html;
}
add_filter('style_loader_tag', 'mytheme_preload_main_css', 10, 2);

ステップ3:Node.jsビルドツールでCSSをMinifyする

// package.json
{
  "scripts": {
    "build:css": "postcss src/css/style.css -o assets/css/style.min.css",
    "watch:css": "postcss src/css/style.css -o assets/css/style.min.css --watch",
    "build": "npm run build:css"
  },
  "devDependencies": {
    "postcss": "^8.4.0",
    "postcss-cli": "^11.0.0",
    "cssnano": "^6.0.0",
    "autoprefixer": "^10.4.0"
  }
}
// postcss.config.js
module.exports = {
    plugins: [
        require('autoprefixer'),           // ベンダープレフィックスを自動付与
        require('cssnano')({               // CSS最小化
            preset: ['default', {
                discardComments: { removeAll: true },
                normalizeWhitespace: true,
                minifyFontValues: true,
            }]
        }),
    ],
};

ステップ4:WordPressでMinify済みCSSを読み込む

// functions.php

function mytheme_enqueue_styles(): void {
    $theme_version = wp_get_theme()->get('Version');

    // 本番環境ではminify済み、開発環境では元ファイルを読み込む
    $css_file = defined('WP_DEBUG') && WP_DEBUG
        ? 'assets/css/style.css'
        : 'assets/css/style.min.css';

    $css_path = get_template_directory() . '/' . $css_file;

    // ファイルの更新日時をバージョンに使う(キャッシュバスティング)
    $version = file_exists($css_path)
        ? filemtime($css_path)
        : $theme_version;

    wp_enqueue_style(
        'mytheme-main',
        get_template_directory_uri() . '/' . $css_file,
        [],
        $version
    );
}
add_action('wp_enqueue_scripts', 'mytheme_enqueue_styles');

ステップ5:wp-config.phpでデバッグモードを切り替える

// wp-config.php(本番環境)
define('WP_DEBUG', false);
define('SCRIPT_DEBUG', false); // falseにするとminify版を使う
// functions.php: SCRIPT_DEBUGを活用する方法
function mytheme_get_asset_url(string $file): string {
    $base = get_template_directory_uri();

    if (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) {
        return $base . '/' . $file;
    }

    // .css → .min.css に置換
    $minified = preg_replace('/\.css$/', '.min.css', $file);
    $min_path  = get_template_directory() . '/' . $minified;

    return file_exists($min_path)
        ? $base . '/' . $minified
        : $base . '/' . $file;
}

注意事項

  • wp-block-library を無効化すると、Gutenbergブロックのスタイルが崩れる場合があります。ブロックエディターを使用したコンテンツがある場合は慎重に判断してください
  • CSSのインライン化は小さいファイル(5KB以下)に限定してください。大きなファイルをインラインにするとHTMLが肥大化してキャッシュの恩恵を受けられなくなります
  • preload による非同期読み込みは、CSSが読み込まれるまでスタイルなしのコンテンツが表示される(FOUC)可能性があります

まとめ

まず wp_dequeue_style で不要なCSSの読み込みを止め、次にクリティカルCSSをインラインに配置してレンダリングブロックを解消します。PostCSSと cssnano でビルド時に自動Minifyし、filemtime でキャッシュバスティングを実装します。SCRIPT_DEBUG 定数で開発・本番を切り替えると管理が楽になります。

お気軽にご相談ください

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