WordPress分类页支持模板选择以实现不同分类不同样式
如果WordPress在新建/编辑页面果可以像Page页面一样选择模板,就可以实现不同分类显示不同样式,想要实现这个需求,有如下几个方案,参考一下。
一、简单粗暴分类ID法
将 category.php 复制多个,分别按分类ID来命名,如下
后面的数字是对应该的分类 ID 号,或者使用 is_category()函数添加判断使用。
二、使用插件方案
插件方法实现分类目录添加模板选项,在 WordPress 后台插件管理页直接搜索安装并启用 Custom Category Template 插件,或直接到 Custom Category Template 插件官方介绍页下载后上传到 wp-content\plugins\ 文件夹内后到后台启用。
三、纯代码方案
在上述插件 Custom Category Template 中提取如下代码,放到主题目录 functions.php 文件中
// 分类选择模板
class Select_Category_Template{
public function __construct() {
add_filter( 'category_template', array($this,'get_custom_category_template' ));
add_action ( 'edit_category_form_fields', array($this,'category_template_meta_box'));
add_action( 'category_add_form_fields', array( &$this, 'category_template_meta_box') );
add_action( 'created_category', array( &$this, 'save_category_template' ));
add_action ( 'edited_category', array($this,'save_category_template'));
do_action('Custom_Category_Template_constructor',$this);
}
// 添加表单到分类编辑页面
public function category_template_meta_box( $tag ) {
$t_id = $tag->term_id;
$cat_meta = get_option( "category_templates");
$template = isset($cat_meta[$t_id]) ? $cat_meta[$t_id] : false;
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="cat_Image_url"><?php _e('Category Template'); ?></label></th>
<td>
<select name="cat_template" id="cat_template">
<option value='default'><?php _e('Default Template'); ?></option>
<?php page_template_dropdown($template); ?>
</select>
<br />
<span class="description"><?php _e('为此分类选择一个模板'); ?></span>
</td>
</tr>
<?php
do_action('Custom_Category_Template_ADD_FIELDS',$tag);
}
// 保存表单
public function save_category_template( $term_id ) {
if ( isset( $_POST['cat_template'] )) {
$cat_meta = get_option( "category_templates");
$cat_meta[$term_id] = $_POST['cat_template'];
update_option( "category_templates", $cat_meta );
do_action('Custom_Category_Template_SAVE_FIELDS',$term_id);
}
}
// 调用所有页面模板
function get_custom_category_template( $category_template ) {
$cat_ID = absint( get_query_var('cat') );
$cat_meta = get_option('category_templates');
if (isset($cat_meta[$cat_ID]) && $cat_meta[$cat_ID] != 'default' ){
$temp = locate_template($cat_meta[$cat_ID]);
if (!empty($temp)){
return apply_filters("Custom_Category_Template_found",$temp);
}
}
return $category_template;
}
}
$cat_template = new Select_Category_Template();
接着建立对应的模板样式,同样将category.php复制多个,然后按样式来命名,无需对应分类ID号,如下
category-style1.php category-style2.php category-style3.php …………
注意,这些分类模板文件的开头都必须添加以下代码:
<?php /* Template Name: 分类模板 - 样式1 */ ?>
Template Name:不能修改,后边的中文部分的命名可以随便修改。
如此操作之后,将在分类编辑时,多出一个“分类目录模板”的选项,选择前边新建的分类目录模板即可。