WordPressの子テーマを使用するとき、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' );
}

親テーマのディレクトリ名を「Template: 」に記述すると、子テーマとして認識される:

/*
 Theme Name:   Destin Child FROG-EIGHT
 Theme URI:    http://frog-eight.com
 Description:  FROG-EIGHT Theme. update 2016/2/14.
 Template:     destin-basic
*/

これらを行い、子テーマのstyle.cssを変更していったのですが、更新がブラウザ側へ送られるstyle.cssに反映されなくなりました。
調べてみると、バージョン番号が指定されていない場合、このようなことが起こるそうです。
参考)https://worklog.be/archives/2983

早速、上記の参考記事を基に以下のコードをfunctions.phpに定義しました。

function my_update_styles( $styles ) {
    $mtime = filemtime( get_stylesheet_directory() . '/style.css' );
    $styles->default_version = $mtime;
}
add_action( 'wp_default_styles', 'my_update_styles' );

filemtime()は、ファイルの更新日時を取得する関数です。これで、ちゃんと子テーマの最新のstyle.cssがブラウザ側に渡されるようになりました。
style.cssのGETパラメータなしでブラウザのURLに指定したときは最新が取れたので、おかしいと思い調べて、上記の記事があってとても助かりました。感謝します!

ブラウザに送られたページのHTMLソースは、こんな感じです。親テーマ、子テーマのstyle.cssに、同じバージョン番号が付与されているのが分かります。

<link rel='stylesheet' id='parent-style-css' href='https://frog-eight.com/wp16/wp-content/themes/destin-basic/style.css?ver=1455510550' type='text/css' media='all' />
<link rel='stylesheet' id='theme_stylesheet-css' href='https://frog-eight.com/wp16/wp-content/themes/child-destin-frog8/style.css?ver=1455510550' type='text/css' media='all' />
(Visited 714 times, 1 visits today)

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です