Shopify Free Trial Apply
Shopify 60天试用
Shopify 14天试用

为WordPress分类添加模板选项

微信图片_20190423115644.png

如上图所示,我们现在使用WordPress做的网站,网站分类的模板默认都是统一的,不像后台添加页面的时候可以随意选择模板。即使我们想要添加不同的模板也只能是根据不同的分类ID或者分类slug来命名这些模板,比如:category-id.php或者category-slug.php。这样添加的话,每个分类都要添加一个模板,工作量巨大。
 
还有一种方法就是根据获取id或者slug,在模板文件里做成判断的形式,但是如果以后增加了分类,就要在模板文件里面再次添加id或者slug,过程繁琐。
 
今天介绍一个插件,可以非常快速的实现我们想要的功能,安装 Custom Category Templates 插件。插件启用后,会在category页面显示分类模板的选择选项。而我们只要制作一两个不同的分类模板即可。分类的模板需要添加一下内容:
    <?php
/*
Template Name: 模板A
*/
?>
以上步骤完成以后,我们就会在分类看到模板选择按钮,如下图所示:
微信图片_20190423120627.png

当然我们也可以在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();
1
2019-04-23

1 个评论

感谢分享好教程。

要回复文章请先登录注册