親テーマのheader.php内でstyle.cssが下記のような形で指定されている時の対処法。
ちょっと無理矢理感があるのでもっとスマートなやり方あれば教えてください。
Design Plusさんで販売されている有料テーマのtcd018で下記のように記載されておりカスタマイズするときに少しつまずいたので私的備忘録。
(あ、Design Plusさんいつも使わせていただいています)
<?php wp_head(); ?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/style.css">
~
子テーマ内のFunctions.phpでCSSを指定する際、公式サイトに書いてある下記コードを記載しても上書きできないという問題が。
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')
);
}
そもそも直書きwp_head();のあとに直書きでcssを読み込んでいるので、子テーマのCSSよりあとに呼びだされてしまう。
このテーマは、テーマオプションでカスタムCSSを登録できるんですが、CSSファイルでどうしても管理したいと思ったので以下のように実装してみました。
対処方法
bodyに子テーマ用のclassをつけ、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_filter('body_class', 'body_classn_names');
function body_classn_names($classes) {
$classes[] = 'child-sample';
return $classes;
}
子テーマのstyle.cssは下記のように変更
.child-sample ●●●指定したい要素●●● {
~~~~~~
}
add_filter('body_class', 'body_classn_names');
~~~
の部分でbodyタグにchild-sampleというclassをつけ、CSSでそれを指定して上書きするだけ。
ちょっと無理矢理感があるかもしれないですが、一応子テーマのfunction.phpで読み込めるしコレでいいかなと。
もっとスマートなやり方あったら誰か教えて下さい。