CSSやJavaScriptをいじった時、いちいちクライアントに「ブラウザのキャッシュをクリアしてください」なんて説明するのは変な話だ。
クライアントがそれで良くても、ユーザーはいちいちキャッシュクリアなんてしない。
自分はCSSのURL末端にstyle.css?ver=20200703
みたいなパラメーターをつけて、CSSを更新するたびにここを書き換えていた。
それを見た同僚がもっと面白い方法を試してくれた。
CSSファイルの更新日時を取得する
filemtime
を使うと、ファイルの更新日時が取得できる。
<?php
$parm = filemtime('style.css');
?>
<link rel="stylesheet" href="style.css?ver=<?php echo $parm; ?>">
WordPressだとこんな感じか。
function main_theme_scripts() {
$parm = filemtime( get_template_directory() . '/style.css' );
wp_enqueue_style(
'theme-style',
get_template_directory_uri() . '/style.css',
array(),
$parm
);
}
add_action( 'wp_enqueue_scripts', 'main_theme_scripts' );
日時のフォーマット
これだけでも機能は果たすが、これまでのような形に日時をフォーマットしたい。
普段ならdate_i18n
を使えばWordPressのタイムゾーンに合わせて変換してくれるのだが、なぜかfilemtime
でこれは使えない。
こちらはダメな例。
function main_theme_scripts() {
date_default_timezone_set('Asia/Tokyo');
$parm = date( 'ymdHi', filemtime( get_template_directory() . '/style.css' ) );
wp_enqueue_style(
'theme-style',
get_template_directory_uri() . '/style.css',
array(),
$parm
);
}
add_action( 'wp_enqueue_scripts', 'main_theme_scripts' );
date_default_timezone_set
してしまうと、WordPressのテーマや他のプラグインの不具合を引き起こす原因になる。
正解はこう。
function main_theme_scripts() {
$parm = date( 'ymdHi', filemtime( get_template_directory() . '/style.css' ) + 3600 * get_option('gmt_offset') );
wp_enqueue_style(
'theme-style',
get_template_directory_uri() . '/style.css',
array(),
$parm
);
}
add_action( 'wp_enqueue_scripts', 'main_theme_scripts' );
gmt_offset
でGMTと現在のタイムゾーンの時差(時間)が取得できる。
単位を秒にしたいので3600秒を掛け算して、結果をfilemtime
に足し算すればOK。
余談
ちなみにテーマのバージョン(style.css
に書くやつ)と一致させるという手もある。
function main_theme_scripts() {
$my_theme = wp_get_theme();
wp_enqueue_style(
'theme-style',
get_template_directory_uri() . '/style.css',
array(),
$my_theme->get( 'Version' )
);
}
add_action( 'wp_enqueue_scripts', 'main_theme_scripts' );
コメント