[WordPress] 子テーマから親テーマのfunctions.phpを変更する

子テーマは親テーマを継承しますが、functions.phpに書いてある内容を変更したい、または削除したい場合があります。
同じ関数名を子テーマに書いて上書きを試みると、「Fatal error: Cannot redeclare」エラーになります。

参考:Overriding WordPress Functions | venutip.com

エラーを回避するには、親テーマでadd_actionされている関数を子テーマでremove_actionしてから別名でadd_actionします。

子テーマのfunctions.php

// Remove the default Thematic blogtitle function
function remove_thematic_actions() {
    remove_action('thematic_header','thematic_blogtitle',3);
}
// Call 'remove_thematic_actions' (above) during WP initialization
add_action('init','remove_thematic_actions');

参考サイトでは、親テーマにある「thematic_header」「thematic_blogtitle」をremoveしています。

関数を書き直す場合は、子テーマに「thematic_header」をコピーしてリネームして親テーマ同様にadd_actionします。

function child_thematic_header() {
 ・
 ・
}
add_action('init', 'child_thematic_header');

<追記>

if (!function_exists('thematic_header')) {
  function thematic_header() {
   ・
  }
}

親テーマ側で「function_exists」でチェックしている場合は、子テーマに同じ関数をコピーして書き換えることもできます。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)