无插件实现WordPress分类目录模板选择功能

WordPress分类目录是一种文章分类的集合,在一些中大型网站中,不同的分类会有不同的版面样式,如果版面类型不多的情况下,可以使用代码进行判断,实现不同分类调用不同的分类目录模板。

但是如果一个网站中的分类目录模板比较多,使用代码判断就比较麻烦了。常用的方法就是给分类目录添加分类目录模板选择功能。这样在网站开发时,就可以自由的选择想显示的模板了。如下图:

怎么给Wordpress分类目录添加模板选择功能呢?方法很简单,只需要将以下的函数代码粘贴到自己使用的模板的模板函数里即可。

/*分类模板选择*/
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();
/*分类模板选择*/

通过这个代码就可以轻松给Wordpress后台分类目录添加模板选择功能了。