問題描述

我正在研究一個小孩主題,我強烈不想覆蓋主模板文件,以保持子主題的簡單性,並儘量減少代碼量和維護時間。

在循環中,父主題中的 index.php 模板使用:get_template_part( 'content' );

這將帶來 content.php,我希望它的行為更像 get_template_part( 'content', get_post_format() ); 或類似的,以便引入不同的模板,如 content-aside.php 等,而不是在子主題中創建一個 index.php 來覆蓋父進行單線更改。

get_template_part()包括:

function get_template_part( $slug, $name = null ) {

    do_action( "get_template_part_{$slug}", $slug, $name );
    $templates = array();
    $name = (string) $name;
    if ( '' !== $name )
        $templates[] = "{$slug}-{$name}.php";

    $templates[] = "{$slug}.php";
    locate_template($templates, true, false);
}

所以有一個動作可用,在我的情況下叫做 get_template_part_content

我可以鈎到具有類似的作用:

add_action( 'get_template_part_content', 'child_post_styles', 10, 2 );

function child_post_styles ( $slug, $name ) {
    if( false == $name ){
        $name = get_post_format();
        $templates = array();
        if ( '' !== $name )
            $templates[] = "{$slug}-{$name}.php";

        $templates[] = "{$slug}.php";
        locate_template($templates, true, false);
    }
}

這顯然導致了重複的重複,一個來自我的掛鈎功能,可以顯示所需的模板,另一個來自 get_template_part()中的正常 locate_template 調用

我無法找到一種方式來完成這個沒有重複,或者沒有結束頁面渲染後,通過做一些愚蠢的服務我的模板部分,如 breakexit

最佳解決方案

沒有鈎子這樣做。將 index.php 複製到子主題,並使單行更改。另外,告訴家長主題的作者,他們應該在主題中做出相同的改變,以實現靈活性。

次佳解決方案

我認為這是不可能實現的方式。真的很煩,沒有得到一個過濾器來改變模板文件名稱:(

我有一個解決辦法。讓 content.php 進行比較。

// content.php file
$format = get_post_format();
if( '' != $format ){
    get_template_part( 'content-'. $format );
}
else{
    get_template_part( 'content-default' );
}

我沒有使用 get_template_part 函數的第二個參數,而是在第一個參數上傳遞了後綴,以避免在 content.php 文件上有不定式的調用,如果沒有'content-'. $format 文件。

參考文獻

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