如何为WordPress分类添加选择不同模板选项-WordPress

资源魔 62 0

咱们有时会依据分类的内容,想让没有同的分类以没有同的款式展现。通常的办法是正在以后主题根目次中多建几个没有同规划款式的分类模板,比方category-1.php、category-2.php、category-3.php.....,前面的数字是对应该的分类ID号,或许应用is_category()函数增加判别,操作有些繁琐。有个更简略的办法,装置 Custom Category Templates 插件。

启用插件后,正在编纂分类时会增加一个抉择模板的选项。

制造几个没有同规划格调的页面模板,模板头部必需有相似的标识:

<?php
/*
Template Name: 模板A
*/

而后正在编纂或许增加分类时,为没有同的分类抉择公用的模板便可。

成果如图:

69e58ca548c9d3069a7129f8875b66a.png

上面是从 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分类增加抉择没有同模板选项的具体内容,更多请存眷资源魔其它相干文章!

标签: WordPress wordpress教程 wordpress自学 wordpress技术

抱歉,评论功能暂时关闭!