【WordPress】子テーマの作成と有効化

WordPressで子テーマを作成する方法と、有効化の手順。

子テーマ用のフォルダを作成する

新規フォルダを作成し、フォルダ名をテーマ名-childとして保存する。

テーマ名は任意の文字列で良いが、親テーマ名を引き継いで命名するとわかりやすい。

親テーマが GicSick の場合、
子テーマは GicSick-child とする。

「style.css」と「functions.php」を作成する

作成したフォルダ内に、style.cssfunctions.phpを作成する。

style.cssを編集する

style.cssを子テーマとして機能させるために必要なコードを記述する。

最低限必要なコードは、親テーマ名子テーマ名の2点。

Theme Nameに子テーマ名、Templateに親テーマのディレクトリ名を記述する。

スタイルシートは次のスタイルシートヘッダで始める必要がある。

/*
 Theme Name:   GicSick Child
 Template:     GicSick
*/

スタイルシートヘッダに記述できるテンプレート情報は以下の通り。

/*
 Theme Name:   Twenty Fifteen Child
 Theme URI:    http://example.com/twenty-fifteen-child/
 Description:  Twenty Fifteen Child Theme
 Author:       John Doe
 Author URI:   http://example.com
 Template:     twentyfifteen
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
 Text Domain:  twenty-fifteen-child
*/

functions.phpを編集する

子テーマのfunctions.phpwp_enqueue_script()を使用し、親テーマのスタイルシートをキューに入れる。

親テーマが 1つの style.css ファイルを使用してすべての CSS を保持している場合

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );

}

テーマが複数の .css ファイルを持つ場合

親テーマに複数のcssファイルがある時は、すべての親テーマの依存関係を管理する必要がある。

依存関係に'parent-style'を設定すると子テーマのスタイルシートは親テーマのあとで読み込まれる。

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

子テーマを有効化する

完成したGicSick-childフォルダをアップロードして有効化する。

  • WordPressのダッシュボード
  • 外観
  • テーマ
  • 新規追加
  • テーマのアップロード

と移動し、GicSick-childフォルダをアップロードする。

そのあと忘れずに有効化する。

有用情報

子テーマは親テーマのすべてのファイルを上書きする

従って、単純に同じ名前のファイルを子テーマディレクトリに置くことで、サイトがロードされると親テーマディレクトリ内の同名のファイルは上書きされる。

ただし、子テーマの functions.php は親の functions.php に追加して読み込まれる

子テーマのfunctions.phpは、親テーマの機能を上書きしない。親テーマのファイルの直前に読み込まれ、親のfunctions.php追加される

子テーマのディレクトリ構造内に存在するファイルをインクルードする場合、get_stylesheet_directory() を使用する

get_stylesheet_directory()は、親テーマのディレクトリでなく、子テーマのディレクトリを指す。

親テーマのstyle.cssは子テーマのstyle.cssで置換され、style.cssは子テーマサブディレクトリのルートディレクトリに存在するため。

Related Tags