【プラグイン不要】WP 子テーマの style.css にクエリパラメータを自動付与する方法

スタイルシート編集後、編集内容がなかなかページに反映されないことがあります。

修正依頼があった際には、その可能性も考慮し、「もし修正が反映されていなかったらリロードしてみて下さい」とクライアントに伝えるようにしていましたが、その一文をメールに書くのもの手間だったりします。
リロードが伝わらないこともあり、やはり確実に修正が反映されるようにしておきたいものです。

目次

修正がページに反映されない原因は?

そもそも修正が反映されない原因は、古い情報が残ってしまっているため。
この古い情報を消去すれば新しい情報が読み込まれるようになりますが、修正の度にそれをしなければいけないのはとても面倒です。

そこで、style.css にクエリパラメータを付与して、更新するたび新しいファイルとして読み込まれるようにします。

要するに、こういう形になります。

<link rel='stylesheet' id='child-style-css'  href='https://office817.com/wp-content/themes/theme-child/style.css?220802141624' type='text/css' media='all' />

style.css の後に ? と数字が並んでいます。
ファイルをアップロードするたび ? 以降の数字が別のものに変わり、常に新しいファイルとして読み込まれるため、「更新されてない、ページが変わってない」という状況を回避できます。

style.css にクエリパラメータを自動付与する

子テーマの functions.php を編集します。
既にサイト運営をしている方であれば下記のようなコードが見つかるはず。

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array('parent-style')
    );
}

これをごそっと下記のコードに書き換えます。

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css?'. date("ymdHis", filemtime( get_stylesheet_directory() . '/style.css')), array('parent-style') );
}

サイト立ち上げ準備中で functions.php が真っ新な状態であれば下記のコードを追加。

<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css?'. date("ymdHis", filemtime( get_stylesheet_directory() . '/style.css')), array('parent-style') );
}
?>

これだけで style.css にクエリパラメータが付与されるようになります。