我尝试在目录和子目录上组织自定义页面模板,但我无法使 WordPress 识别它们。
我已经有一个递归函数来获取以模板路径为键、模板名称为值的关联数组,并修改 wp 缓存,页面模板选择器捕获它们,但是当保存页面时,帖子元包含其他模板;(
获取模板功能
function get_custom_templates($path = null, $templates = array()) {
$parent = "";
if (is_null($path))
$path = get_stylesheet_directory() . "/custom_templates";
else
$parent = basename($path);
foreach (scandir($path) as $item) {
if (substr($item, 0, 1) == ".") continue;
$template = $path . "/" . $item;
if (is_dir($template)) {
$templates = array_merge($templates, get_custom_templates($template, $templates));
} else {
$templates[$template] = $parent . "-" . basename($template, ".php");
}
}
return $templates;
}
将它们添加到编辑器
function include_custom_templates($atts) {
$cache_key = "page_templates-" . md5(get_theme_root() . "/" . get_stylesheet());
$templates = wp_get_theme()->get_page_templates();
if (empty($templates))
$templates = array();
wp_cache_delete($cache_key, "themes");
$templates = array_merge($templates, get_custom_templates());
wp_cache_add($cache_key, $templates, "themes", 1800);
return $attrs;
}
add_filter("page_attributes_dropdown_pages_args", "include_custom_templates");
add_filter("wp_insert_post_data", "include_custom_templates");