問題描述

我想知道有沒有辦法用資料夾使用 get_template_part()?我的主資料夾現在有很多檔案,因為我把每個 re-usable 元素放在一個單獨的檔案中。我想把它們放在資料夾中。

沒有關於食品法典的資訊:http://codex.wordpress.org/Function_Reference/get_template_part

最佳解決方案

其實你可以,我有一個資料夾在我的主題目錄/partials/在那個資料夾我有檔案如 latest-articles.phplatest-news.phplatest-statements.php 和我載入這些檔案使用 get_template_part()像:

get_template_part('partials/latest', 'news');

get_template_part('partials/latest', 'articles');

get_template_part('partials/latest', 'statements');

不要忘了從檔名中省略.php

次佳解決方案

恐怕不是。如果在 codex 中不是您想要知道的內容,請嘗試遵循原始碼連結,並檢視程式碼,並嘗試管理它。

我看了一下,get_template_part 功能定義如下:

function get_template_part( $slug, $name = null ) {
    do_action( "get_template_part_{$slug}", $slug, $name );

    $templates = array();
    if ( isset($name) )
        $templates[] = "{$slug}-{$name}.php";

    $templates[] = "{$slug}.php";

    locate_template($templates, true, false);
}

從中可以看出,get_template_part 功能只是建立一個預期的 php 檔名,並呼叫函式 locate_template 。這沒有用,所以我也看了一下 locate_template 的功能:

function locate_template($template_names, $load = false, $require_once = true ) {
    $located = '';
    foreach ( (array) $template_names as $template_name ) {
        if ( !$template_name )
            continue;
        if ( file_exists(STYLESHEETPATH . '/' . $template_name)) {
            $located = STYLESHEETPATH . '/' . $template_name;
            break;
        } else if ( file_exists(TEMPLATEPATH . '/' . $template_name) ) {
            $located = TEMPLATEPATH . '/' . $template_name;
            break;
        }
    }

    if ( $load && '' != $located )
        load_template( $located, $require_once );

    return $located;
}

找到從 get_template_part 呼叫的 php 檔案的定位模板搜尋。但是你可以直接從你的程式碼中呼叫 locate_template 。這是有用的。

嘗試這個程式碼,而不是 get_template_part(‘loop-sigle.php’) 函式 (您的檔案位於您的主題中的 mydir):

locate_template( 'mydir/loop-single.php', true, true );

參考文獻

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