0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WordPressで子テーマを作るための準備

Last updated at Posted at 2020-12-08

ワードプレスのテーマ twentytwenty を基盤に、子テーマを作る実装を行ったので、備忘録的にこの記事を残す。

環境情報

PHP:version 7.3.12
WordPress:version 5.5.3
WPテーマ:twentytwenty

作業

WordPress の公式テーマなどで配布されているオリジナルテーマに独自に機能を追加したり別のテンプレートを追加したい場合には、「子テーマ」という仕組みを利用します。
もし、オリジナルのテーマを直接変更した場合、テーマのアップデートの際にアップデートの仕組み上最新バージョンのテーマのファイルに上書きされてしまい、自分が行った変更が消えてしまいます。
その状況を防ぐため、親テーマを継承した子テーマを作成してカスタマイズを行う手法をとります。
今回は、例として Twenty Twenty のテーマを継承して作成していきます。「twentytwenty_child」という子テーマを作成します。

ディレクトリとファイルの作成

wp_content/themes 以下に twentytwenty_child というディレクトリを作成し、その中に index.php、style.css、functions.php の3つのファイルを作成する。

style.css の編集

子テーマの style.css に以下を記述する。

style.css
/*
Theme Name: Twenty Twenty Child   <---   子テーマの名前
Author: the WordPress team   <---   子テーマの作成者
Template: twentytwenty   <---   親テーマのディレクトリ名
Description: Twenty Twentyの子テーマです。   <---   テーマの説明
Version: 1.0   <---   子テーマのバージョン
*/

index.php の編集

子テーマの index.php は親テーマの index.php のコピペでよいが、必要に応じて変更箇所を編集することができる。

functions.php の編集

親テーマのスタイルシートを読み込むようにするために、wp_enqueue_scripts をフックに、wp_enqueue_style で style.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' ) );
}

管理画面から有効化

WordPressの管理画面から「外観」>「テーマ」>「Twenty Twenty Child」が表示されるので、「有効化」をクリックします。

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?