問題描述

我想知道有沒有辦法用文件夾使用 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。