需要用于CPT模板的文件夹,例如:Single-{post_type}.php

时间:2018-09-22 作者:Kristian Bendtsen

您好,我觉得我的WP主题文件夹有点乱,有没有办法放置所有自定义页面-{post\\u type}。php和single-{post\\u type}。php放在文件夹中,而不是放在主题的根目录中?。

以及如何确保WP读取它们?提前感谢

1 个回复
SO网友:Kristian Bendtsen

我能解决一些问题

    // defining the sub-directory so that it can be easily accessed from elsewhere as well.
define( \'WPSE_PAGE_TEMPLATE_SUB_DIR\', \'pages\' );

function wpse227006_page_template_add_subdir( $templates = array() ) {
    // Generally this doesn\'t happen, unless another plugin / theme does modifications
    // of their own. In that case, it\'s better not to mess with it again with our code.
    if( empty( $templates ) || ! is_array( $templates ) || count( $templates ) < 3 )
    return $templates;

$page_tpl_idx = 0;
$cnt = count( $templates );
if( $templates[0] === get_page_template_slug() ) {
    // if there is custom template, then our page-{slug}.php template is at the next index 
    $page_tpl_idx = 1;
}

// the last one in $templates is page.php, so
// all but the last one in $templates starting from $page_tpl_idx will be moved to sub-directory
for( $i = $page_tpl_idx; $i < $cnt - 1; $i++ ) {
    $templates[$i] = WPSE_PAGE_TEMPLATE_SUB_DIR . \'/\' . $templates[$i];
}

return $templates;
}
// the original filter hook is {$type}_template_hierarchy,
// wihch is located in wp-includes/template.php file
add_filter( \'page_template_hierarchy\', \'wpse227006_page_template_add_subdir\' );
但是我仍然在为我的单{post type}寻找相同的解决方案。php页面要放在文件夹中。对于我的分类法-{分类法名称}。php:)如果有人能帮我指引正确的方向。

结束

相关推荐

子主题的GET_STYLESET_DIRECTORY()与GET_TEMPLATE_DIRECTORY()的比较

假设我的父主题文件夹中有以下文件:\'theme-folder/inc/custom.php\'然后我创建了一个儿童主题。如何检查该文件是否存在于子主题中,然后获取它,否则从父主题获取它?get_template_directory() 始终从父主题获取文件。虽然get_stylesheet_directory() 要求文件存在于子主题中。