在插件中包含模板文件。我把我的贴在/插件/模板上。
您需要挂接到该模板的模板位置:
add_filter(\'archive_template\', \'yourplugin_get_custom_archive_template\');
function yourplugin_get_custom_archive_template($template) {
global $wp_query;
if (is_post_type_archive(\'yourCPT\')) {
$templates[] = \'archive-yourCPT.php\';
$template = yourplugin_locate_plugin_template($templates);
}
return $template;
}
冲洗并对要实现的每个模板(单个、分类法等)进行适当的检查,然后重复操作。
function yourplugin_locate_plugin_template($template_names, $load = false, $require_once = true ) {
if (!is_array($template_names)) {
return \'\';
}
$located = \'\';
$this_plugin_dir = WP_PLUGIN_DIR . \'/\' . str_replace( basename(__FILE__), "", plugin_basename(__FILE__));
foreach ( $template_names as $template_name ) {
if ( !$template_name )
continue;
if ( file_exists(STYLESHEETPATH . \'/\' . $template_name)) {
$located = STYLESHEETPATH . \'/\' . $template_name;
break;
} elseif ( file_exists(TEMPLATEPATH . \'/\' . $template_name) ) {
$located = TEMPLATEPATH . \'/\' . $template_name;
break;
} elseif ( file_exists( $this_plugin_dir . \'/templates/\' . $template_name) ) {
$located = $this_plugin_dir . \'/templates/\' . $template_name;
break;
}
}
if ( $load && $located != \'\' ) {
load_template( $located, $require_once );
}
return $located;
}
这样做意味着WP将首先在主题中查找模板,但如果在主题中找不到模板,则会返回插件的模板文件夹。如果用户想要修改模板以适应其主题,他们只需将其复制到主题文件夹中即可。
如果你真的想聪明一点,你可以强制检查他们的主题文件夹中的模板,如果他们使用插件的模板副本,可以加载一些默认样式:
add_action(\'switch_theme\', \'yourplugin_theme_check\');
add_action(\'wp_enqueue_scripts\', \'yourplugin_css\');
function yourplugin_css() {
if(get_option(\'yourplugin-own-theme\') != true && !is_admin()) {
wp_enqueue_style(\'yourplugin-styles\', plugins_url(\'/css/yourplugin.css\', __FILE__));
}
}
function yourplugin_theme_check() {
if(locate_template(\'archive-yourCPT.php\') != \'\' && locate_template(\'single-yourCPT.php\') != \'\' && locate_template(\'taxonomy-yourTaxonomy.php\') != \'\' && locate_template(\'taxonomy-anotherTaxonomy.php\') != \'\') {
update_option(\'yourplugin-own-theme\', true);
}
else {
update_option(\'yourplugin-own-theme\', false);
}
}