【WordPress】子テーマのfunctions.php内で’after_setup_theme’を使っても無駄な時の対策
親テーマのfunctions.phpがrequire_once()でファイルを読み込んでて子テーマでの上書きに苦労した話
WooCommerce機能付きのテーマを子テーマを作って弄っていたら親テーマのfunctions.php内に
if (class_exists('Woocommerce')) {
require_once( get_template_directory() . '/woocommerce/config.php');
}
こう書いてありました。
子テーマからこのwoocommerce/config.phpファイル内にある関数を弄りたくて、まず子テーマにもwoocommerce/config.phpを作りfunctions.php内にremove_actionだったり引数に’after_setup_theme’を加えたりと色々試しましたが中々子テーマのconfig.phpだけを読み込ますのに苦労しました。(結論から言うと無理でした。)
WordPress関数のadd_action()と違ってrequire_once()はphpの組み込み関数なので子テーマからremoveしたりすることはできません。
どう足掻いても親テーマの方のみか両方しか読み込めませんでした。
というわけなので結局子テーマのfunctions.php内に
if (class_exists('Woocommerce')) {
require_once( get_stylesheet_directory() . '/woocommerce/config.php');
}
と記述し、子テーマのconfig.phpは一旦真っ新なPHPファイルにした後に
add_action( 'after_setup_theme', 'remove_parent_wcconfig', 0 );
function remove_parent_wcconfig() {
//remove_actionの引数は上書きしたいadd_actionと同一
remove_action( '第1引数', '第2引数','(指定されていれば)上書きしたいadd_actionの第3引数' );
}
add_action('上書きしたいadd_actionの第1引数','関数名');
function 関数名() {
//上書きしたい関数
}
こんな感じで期待通りの動作をしてくれました。
めでたしめでたし。
参考記事
Include files in child theme functions file
https://wordpress.stackexchange.com/questions/3293/include-files-in-child-theme-functions-file
remove_action on after_setup_theme not working from child theme
https://wordpress.stackexchange.com/questions/170663/remove-action-on-after-setup-theme-not-working-from-child-theme