tohokuaikiのチラシの裏

技術的ネタとか。

WordPressでの子テーマにおける正しいCSSの読み込み方

なんかイマイチな呼び出し方

子テーマ、便利ですよね。

で、ちょっと上書きしたいCSSを定義したいなーって思って「子テーマ CSS WordPress」あたりで検索するとこんな感じで出てきます。
このエントリで否定する例なので出してしまって申し訳ないのですが…

でも、これを例えばpenmanというテーマの子テーマを作って、子テーマのfunctions.phpに書いてやると、

<?php
add_action( 'wp_enqueue_scripts', function() {
    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'));

<link rel='stylesheet' id='parent-style-css'  href='https://example.jp/wp-content/themes/penman/style.css?ver=5.3.2' type='text/css' media='all' />
<link rel='stylesheet' id='child-style-css'  href='https://example.jp/wp-content/themes/penman-child/style.css?ver=5.3.2' type='text/css' media='all' />
<link rel='stylesheet' id='penman-style-css'  href='https://example.jp/wp-content/themes/penman-child/style.css?ver=5.3.2' type='text/css' media='all' />

って、子テーマのCSSを2回読んでしまうんです。

何がイマイチかっていうと…

それくらいいじゃんっていう感じなのですが、CSSをアップデートしてキャッシュ対策をしたい場合

<?php
add_action( 'wp_enqueue_scripts', function() {
    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'), '20200109');

とかしますよね。でも、出てくるHTMLは

<link rel='stylesheet' id='parent-style-css'  href='https://example.jp/wp-content/themes/penman/style.css?ver=5.3.2' type='text/css' media='all' />
<link rel='stylesheet' id='child-style-css'  href='https://example.jp/wp-content/themes/penman-child/style.css?ver=20200109' type='text/css' media='all' />
<link rel='stylesheet' id='penman-style-css'  href='https://example.jp/wp-content/themes/penman-child/style.css?ver=5.3.2' type='text/css' media='all' />

って、「それ、古いCSSのキャッシュで上書きしちゃってるじゃん!!!」って感じなんですよね。バージョンをアップしてもひたすら意味ないです。

ということで、正しい子テーマのCSS読み方は

<?php
add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_style( 'parent-penman-style', get_template_directory_uri() . '/style.css' , array(), '20200109-p');
    wp_enqueue_style( 'penman-style', get_stylesheet_directory_uri() . '/style.css', array('parent-penman-style'), '2020010p-c');

ってします。このwp_enqueue_styleの2行は前後どっちでもいいですが、2行目の依存関係が分かりやすいようにしています。

解説

1行目のwp_enqueue_styleで親テーマのCSSを読みこみます。この時、名称は親テーマのCSS名称と同じにしてはいけません。

2行目のwp_enqueue_styleで子テーマのCSSを読みこみます。この時、名称は親テーマのCSS名称と同じにします。更に、依存性で1行目の親テーマのCSSを先に指定することで親テーマのCSSの後でロードされます。

問題があるとすると

親テーマを更新した際に、この子テーマのfunctions.phpのバージョン設定「20200109-p」を新しい文字にしないといけない所ですね。

まあ、面倒なら、親テーマのstyle.cssのタイムスタンプかmd5でも付けちゃえばいいのでは。