問題描述

例如,在我的博客頁面上,我使用 get_header('blog');,但我不想創建一個名為 header-blog.php 的新標題模板,因為我只是想做一個小的調整。有可能以某種方式在我的 header.php 文件中獲取此名稱參數?

最佳解決方案

有一個可以使用的動作 get_header 。在您的主題 functions.php 中,為該操作註冊回調:

add_action( 'get_header', function( $name ) {
    add_filter( 'current_header', function() use ( $name ) {
        // always return the same type, unlike WP
        return (string) $name;
    });
});

你也可以編寫一個可以重用的小幫手類:

class Template_Data {

    private $name;

    public function __construct( $name ) {

        $this->name = (string) $name;
    }

    public function name() {

        return $this->name;
    }
}

add_action( 'get_header', function( $name ) {
    add_filter( 'current_header', [ new Template_Data( $name ), 'name' ] );
});

在您的 header.php 中,您將獲得當前的零件/名稱:

$current_part = apply_filters( 'current_header', '' );

您可以使用 get_footerget_sidebarget_template_part_{$slug}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。