しばたの備忘録

プロフィール画像はどっかで拾って来た4096分音符。

子テーマがようやくできた。

店のウェブサイトはWordPressを使ってるんだけど、テーマのアップデートの度に書き換えたところがリセットされてしまって困ってたんですが、そんなときのために子テーマなんてものがあるんですね。

前から「子テーマ」という単語は聞いたことがあったんですが、プロが使うものだから関係ないと今までシカトしてました。

 

早速作ってみたんですが、子テーマを有効化させると親テーマと違うレイアウトになってしまってそれを治す術がわからず、しばらく往生してたんですが、解決したので覚え書き。 

 

基本的に、style.cssとfunctions.phpしか触らないので、そのどっちかの記述が間違ってるんだろうとは思ってました。

その時参考にしたサイトは、

1. 子テーマのstyle.cssで親テーマを変更したらレイアウトが崩れてしまったとき | 西沢直木のIT講座

2. つまづいたところ – 子テーマの有効化でレイアウトが崩れる。。 – wordpress – 徒然日記

3. WordPress子テーマCSSを反映させる、新しいやり方。@import urlから変更。 | ラビットしま子のカスタム備忘録Exciting

 

これらのサイトは、Googleで「子テーマ レイアウト 変わる」で検索して上位に表示されたサイトです。

結論から言うと全部うまくいきませんでした。

1〜3の記事はstyle.cssについてはそれぞれほとんど書いてあることは一緒なんですが、functions.phpの書き方がちょっと違うようでした。

1. functions.phpについて言及なし。
親テーマから子テーマに変更する際に、適当な他のテーマを経由して変更する、と言う手順です。

Customizer Export/Import — WordPress Plugins

こんなプラグインもあるので有効なのかもしれませんがうまくいきませんでした。

 

2. functions.phpの記述パターン(1)

<?php
add_action( ‘wp_enqueue_scripts’, ‘theme_enqueue_styles’ );
function theme_enqueue_styles() {
wp_enqueue_style( ‘parent-style’, get_template_directory_uri() . ‘/style.css’ );
}

 

3.functions.phpの記述パターン(2)

<?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')
);
}

 

WordPressについてほとんど知識がなく、上記サイトでも「function.php」「functions.php」とただの誤字なのかわからない違いがあったり、そもそもここに書いてないだけで、何かしら前提となる記述が必要なのかと勘ぐったりしてました。

その後、私が使っているテーマの提供元のサイトをみてみることにしました。

(結論から言うと、ここで解決したので最初からここを見ればよかったのですが、何せ英語のサイトだったのでそれだけで敬遠してました。)

4. 🎥 How to create a Child theme - ThemeIsle Docs

functions.phpの記述パターン(3)

<?php
add_action( 'wp_enqueue_scripts', 'child_enqueue_styles',99);
function child_enqueue_styles() {
$parent_style = 'parent-style';
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 ) );
}
if ( get_stylesheet() !== get_template() ) {
add_filter( 'pre_update_option_theme_mods_' . get_stylesheet(), function ( $value, $old_value ) {
update_option( 'theme_mods_' . get_template(), $value );
return $old_value; // prevent update to child theme mods
}, 10, 2 );
add_filter( 'pre_option_theme_mods_' . get_stylesheet(), function ( $default ) {
return get_option( 'theme_mods_' . get_template(), $default );
} );
}

詳しいことはさっぱりわかりませんが、上記の記述をfunctions.phpに貼り付けたら上手いこといきました。2.が一番シンプルに書いてあって、その後3.では赤い箇所が増え、4.で緑色の箇所がさらに追加されています。

途中2.と3.では'theme_enqueue_styles'、4.で'child_enqueue_styles'って箇所がありますが、これは多分この中だけで完結している関数?だと思うので変わってるわけじゃないと思います。