見出し画像

【WordPress】子テーマの作成方法

子テーマとは?

あるWordPressテーマにカスタマイズを加えたい場合、直接テーマを編集してしまうと、テーマがアップデートされる際にそれが上書きされてしまいます。
そこで、元のテーマの「子テーマ」を別途作成し、そちらに変更を加えていくことでそのような上書きも回避でき、管理がしやすくなります。
仕組みとしては、親テーマと子テーマに同じPHPファイルが存在する場合は、子テーマのファイルが優先して読み込まれます。
なので、変更したファイルだけを子テーマに配置すればOK。

作成の流れ

1.テーマフォルダを作成
2.style.cssを作成
3.functions.phpを作成
4.テーマをアップロード・選択

1.テーマフォルダを作成

フォルダを作成します。名称はなんでもOK。
分かりやすい方がよいので「親テーマ名-child」とかが良いのでは。

2.style.cssを作成

子テーマディレクトリ直下に作成。
以下の内容を記載します。

(1)子テーマ名 ・・何でもOK(「親テーマ名 + Child」とか)
(2)親テーマのフォルダ名 ・・フォルダ名を正確に。
/*
Theme Name: 子テーマ名
Template: 親テーマフォルダ名
*/

3.functions.phpを作成

以下を記載。

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

※カスタマイズがあれば、この間に追加していく

?>

JSファイルやCSSを読み込む場合も、こちらのfunctions.phpに記載する。
以下、記載例。(JSの読み込みと、外部CDNのCSS読み込みを追加)

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

 //jsの読み込み
 wp_enqueue_script( 'child-js', get_stylesheet_directory_uri() . '/js/main.js', array(), '', true );
}

// FontAwesomeのCSS読み込み
add_action('wp_head', 'script_fa_cdn');
function script_fa_cdn(){
  $link = <<<EOT
    <link href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" rel="stylesheet">
  EOT;
echo $link;
};

?>

4.テーマをアップロード・選択

管理画面やFTPを使って、子テーマをサーバにアップしましょう。
テーマ選択ページに子テーマが反映されてなければ、何か問題があるはずなので確認。

よくある上手く行かない原因
・親にしてるテーマが既に子テーマ
・style.cssの「Template」がフォルダ名と違う(テーマ名ではなくフォルダ名を!)

補足:TCDテーマ等でデザインが崩れる場合

TCDテーマ(有名な有料WPテーマ)の子テーマを作成した場合にそのままだとデザインが崩れてしまう場合があります。
その場合には以下の対応で解決。

1.親テーマのheader.phpを子テーマ内にコピペ
2.子テーマ内のheader.phpを以下のように書き換え

子テーマの方のheader.php内を、以下の通り置換。

bloginfo('stylesheet_directory');



echo get_template_directory_uri();

補足:JSファイルの読み込み方法

1.jsファイルを任意の場所にアップ
2.子テーマのfunctions.phpに読み込みの記載を追加

以下の記載を子テーマのfunctions.phpに追加

  //jsの読み込み
 wp_enqueue_script( 'child-js', get_stylesheet_directory_uri() . '/js/main.js', array(), '', true );

記載例:

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

 //jsの読み込み
 wp_enqueue_script( 'child-js', get_stylesheet_directory_uri() . '/js/main.js', array(), '', true );
}

参考:




この記事が気に入ったらサポートをしてみませんか?