WordPress

  • プラグイン領域でのget_template_partの上書き

    get_template_part(‘foo’);はテーマ領域で手繰ってくるものなので、プラグイン領域で使おうとすると詰む。

    • [theme]/template-parts/some-template.phpの処理を上書きしたいが、テーマ及び子テーマを編集せずに済ませたいときなどに使えるかも。
    • 基本的な考え方は、結局のところload_templateで呼び出してるので、get_template_partにアクションフックかけりゃいい
    • サーバーOSのことを考えるなら ‘/’ でやるよりは DIRECTORY_SEPARATORでやった方がいいのかも

    概略

    add_action(‘get_template_part’,function($slug,$name,$template,$args){ DO_SOMETHING }, 10,4);

    アクション登録

    $target_template_names=[‘template-parts/foo.php’];

    書き換えたいテンプレートのパスを配列かなんかで保持

    $template[0]と$target_template_names[n]で比較

    合致したら処理

    load_template($override_template_path,true,$args);

    読み込み先のテンプレートを読み込む