WordPress将仅从主题的根目录中搜索一个级别的深度(*请参阅下面的详细信息),以查找页面(和帖子)模板。
但是,可以使用theme_{$post_type}_templates
筛选,以便您可以自己添加深度嵌套的模板:
// See WP_Theme::get_page_templates
/**
* Filters list of page templates for a theme.
*
* The dynamic portion of the hook name, `$post_type`, refers to the post type.
*
* @since 3.9.0
* @since 4.4.0 Converted to allow complete control over the `$page_templates` array.
* @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.
*/
function wpse249984_add_templates( $post_templates, $wp_theme, $post, $post_type ) {
$post_templates[\'folder-1/child-folder-1/my-template.php\'] = \'My Template\';
return $post_templates;
}
add_filter( \'theme_page_templates\', \'wpse249984_add_templates\', 10, 4 );
*详细信息:查看
/wp-includes/class-wp-theme.php.
深度1
是硬编码的,无法更改。在里面WP_Theme::get_post_templates()
, 重要的一点是$files = (array) $this->get_files( \'php\', 1 );
, 哪里1
是$depth
论点
/**
* Returns the theme\'s post templates.
*
* @since 4.7.0
* @access public
*
* @return array Array of page templates, keyed by filename and post type,
* with the value of the translated header name.
*/
public function get_post_templates() {
// If you screw up your current theme and we invalidate your parent, most things still work. Let it slide.
if ( $this->errors() && $this->errors()->get_error_codes() !== array( \'theme_parent_invalid\' ) ) {
return array();
}
$post_templates = $this->cache_get( \'post_templates\' );
if ( ! is_array( $post_templates ) ) {
$post_templates = array();
$files = (array) $this->get_files( \'php\', 1 );
foreach ( $files as $file => $full_path ) {
...
return $post_templates;
}
。。。
/**
* Return files in the theme\'s directory.
* @param mixed $type Optional. Array of extensions to return. Defaults to all files (null).
* @param int $depth Optional. How deep to search for files. Defaults to a flat scan (0 depth). -1 depth is infinite.
* @param bool $search_parent Optional. Whether to return parent files. Defaults to false.
* @return array Array of files, keyed by the path to the file relative to the theme\'s directory, with the values
* being absolute paths.
*/
public function get_files( $type = null, $depth = 0, $search_parent = false ) {
...
}