/您的主题/页面模板/仅适用于在管理页面编辑屏幕上分配的自定义页面模板,而不适用于页面-$slug或页面-$id命名模板。
在我的视图中,正确的过滤器挂钩是page\\u template,但您没有(我假设!)想为你的页面扔掉任何其他可能的模板,尤其是因为你的网站上一定会有一些页面,而你还没有为这些页面创建一个/my sub dir/page-slug。php模板文件。
在WP使用标准模板层次结构找到页面的模板后,立即调用page\\u template筛选器挂钩。如果有一个过滤器可以让您将额外的模板注入模板层次结构的正确部分,这将非常方便,但如果没有过滤器,我们需要从WordPress自己的get\\u page\\u template()函数中复制对页面模板的搜索,该函数位于/wp includes/template中。php:
function get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var(\'pagename\');
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = get_queried_object();
if ( $post )
$pagename = $post->post_name;
}
$templates = array();
if ( $template && 0 === validate_file( $template ) )
$templates[] = $template;
if ( $pagename )
$templates[] = "page-$pagename.php";
if ( $id )
$templates[] = "page-$id.php";
$templates[] = \'page.php\';
return get_query_template( \'page\', $templates );
}
此函数用于为页面构建一组可能的模板。get\\u query\\u template()然后使用locate\\u template()遍历数组并返回找到的第一个模板的文件名。
由于我们无法连接到提议的模板列表中,很遗憾,我们将不得不重复一些这项工作。
以下是我们自己的功能:
function tbdn_get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var(\'pagename\');
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = get_queried_object();
if ( $post )
$pagename = $post->post_name;
}
$templates = array();
if ( $template && 0 === validate_file( $template ) )
$templates[] = $template;
// if there\'s a custom template then still give that priority
if ( $pagename )
$templates[] = "our-sub-dir/page-$pagename.php";
// change the default search for the page-$slug template to use our directory
// you could also look in the theme root directory either before or after this
if ( $id )
$templates[] = "our-sub-dir/page-$id.php";
$templates[] = \'page.php\';
/* Don\'t call get_query_template again!!!
// return get_query_template( \'page\', $templates );
We also reproduce the key code of get_query_template() - we don\'t want to call it or we\'ll get stuck in a loop .
We can remove lines of code that we know won\'t apply for pages, leaving us with...
*/
$template = locate_template( $templates );
return $template;
}
add_filter( \'page_template\', \'tbdn_get_page_template\' );
注意事项:
1-我还没有对此进行测试,但如果你想搞乱模板层次结构,那么你肯定能够遵循,测试&;调整我的代码,这主要是复制自WP无论如何。
2-如果将来的核心代码更改了页面的模板层次结构,那么上面的代码将过时。