我想知道是否可以将get_template_part()与文件夹一起使用?我的主文件夹现在有很多文件,因为我将每个可重复使用的元素都放在了单独的文件中。那我想把它们放在文件夹里。
在Codex中没有关于此的信息:http : //codex.wordpress.org/Function_Reference/get_template_part
我想知道是否可以将get_template_part()与文件夹一起使用?我的主文件夹现在有很多文件,因为我将每个可重复使用的元素都放在了单独的文件中。那我想把它们放在文件夹里。
在Codex中没有关于此的信息:http : //codex.wordpress.org/Function_Reference/get_template_part
Answers:
实际上,您可以,在主题目录中有一个文件夹,/partials/该文件夹中有个文件,例如latest-articles.php,latest-news.php然后latest-statements.php使用以下方式加载这些文件get_template_part():
get_template_part('partials/latest', 'news');
get_template_part('partials/latest', 'articles');
get_template_part('partials/latest', 'statements');只是不要忘记.php从文件名中省略。
<?php get_template_part('partials/file'); ?>
                    恐怕不是。如果您不想知道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 );功能get_template_part()说明:
注意
-用法:locate_template()
-用法:do_action()调用“ get_template_part _ {$ slug}”操作。
Wich允许您使用locate_template(),它说:
在TEMPLATEPATH之前的STYLESHEETPATH中进行搜索,以便从父主题继承的主题可以使一个文件过载。
如果TEMPLATEPATH使用要使用的子目录进行定义,将在子目录中get_template_part()搜索文件。