WordPress の一般的な functions.php はフラットに関数が並ぶ形ですが、Habakiri では子テーマから各処理を上書きしやすくするために、functions.php に PHP のクラスを使用しています。クラスを使うことでプレフィックスも気にしなくてよくなるので便利です。

子テーマで Habakiri の functions.php を継承する

子テーマの functions.php でafter_setup_themeアクションに関数をフックさせ、その関数内で Habakiri の functions.php を継承させます。Habakiri に用意されているクラスメソッドと同じ名前のメソッドを定義することでそのメソッドを上書きできます。

<?php
function habakiri_child_theme_setup() {
	class Habakiri extends Habakiri_Base_Functions {

		// 例えば、テーマカスタマイザーを呼び出すメソッド ( customizer ) を上書きして
		// テーマカスタマイザーを無効にする
		public function customizer() {
		}
	}
}
add_action( 'after_setup_theme', 'habakiri_child_theme_setup' );

フックを使用する

子テーマクラスの中でフックを使用する場合は、コンストラクタの中でadd_filteradd_actionすると便利です。ここで大事なのは、コンストラクタの中で、親である Habakiri のコンストラクタを呼ぶことです。これをしないといろいろなところに不具合がでるので必ず忘れないようにしてください。

<?php
function habakiri_child_theme_setup() {
	class Habakiri extends Habakiri_Base_Functions {

		public function __construct() {
			// Habakiri のコンストラクタを実行
			parent::__construct();

			// pre_get_posts アクションにフック
			add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ) );

			// the_content フィルターにフック
			add_filter( 'the_content', array( $this, 'the_content' ) );

		}

		// pre_get_posts アクションにフックさせるメソッド
		public function pre_get_posts( $query ) {
		}

		// the_content フィルターにフックさせるメソッド
		public function the_content( $content ) {
			return $content;
		}
	}
}
add_action( 'after_setup_theme', 'habakiri_child_theme_setup' );

一般的な functions.php と同じように関数ベースでフックの処理を書くこともできます。その場合はクラスの外に処理を書けば大丈夫です。

<?php
function habakiri_child_theme_setup() {
	class Habakiri extends Habakiri_Base_Functions {
		〜 省略 〜
	}
}
add_action( 'after_setup_theme', 'habakiri_child_theme_setup' );


function my_the_content( $content ) {
	return $content;
}
add_filter( 'the_content', 'my_the_content' );