下面由wordpress教程栏目给大家为wordpress分类添加选择不同模板选项的方法,希望对需要的朋友有所帮助!
我们有时会根据分类的内容,想让不同的分类以不同的样式展示。通常的方法是在当前主题根目录中多建几个不同布局样式的分类模板,比如category-1.php、category-2.php、category-3.php.....,后面的数字是对应该的分类id号,或者使用is_category()函数添加判断,操作有些繁琐。有个更简单的方法,安装 custom category templates 插件。
启用插件后,在编辑分类时会添加一个选择模板的选项。
制作几个不同布局风格的页面模板,模板头部必须有类似的标识:
<?php/*template name: 模板a*/
然后在编辑或者添加分类时,为不同的分类选择专用的模板即可。
效果如图:
下面是从 custom category templates 插件中提取出来的代码,可以直接添加到当前主题函数模板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();
以上就是如何为wordpress分类添加选择不同模板选项的详细内容。