编辑自定义模板选择器

问题描述 投票:0回答:1

我尝试在目录和子目录上组织自定义页面模板,但我无法使 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");
php wordpress
1个回答
0
投票

来自页面模板

WordPress 可以识别子文件夹页面模板。因此,最好将全局页面模板存储在此文件夹中,以帮助保持它们井然有序。

WP 3.4开始就是这样。

所以我的建议是将它们放在主题中的

/page-templates
子目录中,而不是
/custom_templates
中。这样,您的 WordPress 就会立即识别它们。

© www.soinside.com 2019 - 2024. All rights reserved.