CorePress使用插件的方式添加文章和页面模板

网上的方法都比较麻烦,整理了一下代码,只需要替换页面名称和页面路径即可

define('CP_PLUGIN_DIR', plugin_dir_path(__FILE__));
$cp_page_templates = array(
    array("slug" => "page-corepress.php",
        "name" => "CorePress-Pro主题页面",
        "path" => CP_PLUGIN_DIR . "/page-corepress.php",
    ),
);
add_filter('page_template', 'cp_page_template');
add_filter('single_template', 'cp_page_template');
function cp_page_template($page_template)
{
    global $cp_page_templates;
    $slug = get_page_template_slug();
    foreach ($cp_page_templates as $item) {
        if ($slug == $item['slug']) {
            $page_template = $item['path'];
        }
        return $page_template;
    }
}
add_filter( 'theme_page_templates', 'cp_page_add_template_to_select', 10, 4 );
add_filter( 'theme_post_templates', 'cp_page_add_template_to_select', 10, 4 );

function cp_page_add_template_to_select( $post_templates, $wp_theme, $post, $post_type ) {
    global $cp_page_templates;
    foreach ($cp_page_templates as $item) {
        $post_templates[$item['slug']] = $item['name'];
    }
    return $post_templates;
}

其中,只需要修改$cp_page_templates变量里面的参数即可,slug为文件名称,name为模板名称,path为文件路径。多个模板,多添加几个array即可。

另外用的时候,建议也改一改常量CP_PLUGIN_DIR,改成唯一的名字。

 

THE END