不久前我开始了一个新的 Wordpress 项目。但是我遇到了一个问题。由于有多种设计,我需要为不同页面模板上的页面、帖子和文本格式输出创建多个模板。
因为模板文件太多,我想创建一些子目录。我知道自 Wordpress 3.4 及更高版本以来,您可以将子目录名称 page-templates
用于所有页面模板,但我如何将其用于格式文件和发布文件。
是的,我确实尝试添加如下功能:
get_template_part('/template-parts/page-templates' , 'page');
和
require( get_template_directory() . '/template-parts/template-tags.php' );
我想创建的理想目录结构如下:
wp-content/themes/mytheme
- archive
- 404
- CSS
- JS
- Images
- template-parts (dir)
-- page-templates (dir for page-template files.)
-- format-templates (dir for format-templates.)
-- post-templates (dir for post-templates.)
- header
- footer
所以要清楚。我想为上面的模板文件创建结构。不要介意 CSS
等文件夹。它们的设置方式正确。目的是,在我成功创建结构后,能够从 /wp-admin
编辑页面部分选择模板,如页面模板。
最佳答案
WP_Theme
类包含提供此过滤器的方法 get_page_templates()
:
apply_filters( "theme_{$post_type}_templates", $post_templates, $this, $post, $post_type );
line 1103 of class-wp-theme.php
请记住,在 wordpress 中 post
和 page
是 post_type
小号,
add_filter( "theme_post_templates", ...
和 add_filter( "theme_page_templates",...
应该是有效的。
Under the codex's "Used By" section对于该方法,它指出:
wp-admin/includes/template.php: page_template_dropdown()
wp-admin/includes/meta-boxes.php: page_attributes_meta_box()
这让我相信它会让它们在 /wp-admin/
编辑页面部分可用。
核心文件中有关过滤器的信息:
* Filters list of page templates for a theme.
*
* The dynamic portion of the hook name, `$post_type`, refers to the post type.
* @since 4.7.0 Added the `$post_type` parameter.
*
* @param array $post_templates Array of page templates. Keys are filenames,
* values are translated names.
* @param WP_Theme $this The theme object.
* @param WP_Post|null $post The post being edited, provided for context, or null.
* @param string $post_type Post type to get the templates for.
我不确定相对 uri 在这里是否有效,或者您是否需要 get_theme_file_path()
,但我假设是前者。
function deep_templates( $post_templates, $theme, $post, $post_type )
$post_templates['/folder/folder/folder/file.php'] = "Page Style One";
$post_templates['/folder/other-folder/file.php'] = "Page Style Two";
return $post_templates;
add_filter( 'theme_page_templates', 'deep_templates' );
和/或
add_filter( 'theme_post_templates', 'deep_templates' );
add_filter( 'theme_my-custom-cpt_templates', 'deep_templates' );
关于php - 子目录中的 Wordpress 模板文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44261944/