LoginSignup
1
1

More than 5 years have passed since last update.

【Wordpress】親テーマでCSSを直書きしている時に子テーマのCSSで変更する方法

Last updated at Posted at 2016-01-14

親テーマのheader.php内でstyle.cssが下記のような形で指定されている時の対処法。
ちょっと無理矢理感があるのでもっとスマートなやり方あれば教えてください。

Design Plusさんで販売されている有料テーマのtcd018で下記のように記載されておりカスタマイズするときに少しつまずいたので私的備忘録。
(あ、Design Plusさんいつも使わせていただいています)

header.php
<?php wp_head(); ?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/style.css">
~

子テーマ内のFunctions.phpで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')
    );
}

そもそも直書きwp_head();のあとに直書きでcssを読み込んでいるので、子テーマのCSSよりあとに呼びだされてしまう。
このテーマは、テーマオプションでカスタムCSSを登録できるんですが、CSSファイルでどうしても管理したいと思ったので以下のように実装してみました。

対処方法

bodyに子テーマ用のclassをつけ、CSSを書き直す。
子テーマのfunctions.phpを以下のように変更。

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は下記のように変更

style.css
.child-sample ●●●指定したい要素●●● {
~~~~~~
}

add_filter('body_class', 'body_classn_names');
~~~
の部分でbodyタグにchild-sampleというclassをつけ、CSSでそれを指定して上書きするだけ。

ちょっと無理矢理感があるかもしれないですが、一応子テーマのfunction.phpで読み込めるしコレでいいかなと。
もっとスマートなやり方あったら誰か教えて下さい。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1