给 wordpress Category (分类)添加字段

1.  在模板目录下的 function.php 里添加包含 页面 category_field.php

包括代码如下:

// 分类添加字段
require_once( dirname(__FILE__).'/category_field.php' );
2.  新建 category_field.php 页面

代码如下:

<?php 
// 分类添加字段
function ems_add_category_field(){
	echo '<div class="form-field">
			<label for="cat-tel">Tel</label>
			<input name="cat-tel" id="cat-tel" type="text" value="" size="40">
			<p>The telephone.</p>
		  </div>';	
	echo '<div class="form-field">
			<label for="cat-url">URL</label>
			<input name="cat-url" id="cat-url" type="text" value="" size="40">
			<p>The URL.</p>
		  </div>';		  
		  
}
add_action('category_add_form_fields','ems_add_category_field',10,2);

// 分类编辑字段
function ems_edit_category_field($tag){
	echo '<tr class="form-field">
			<th scope="row"><label for="cat-tel">Tel</label></th>
			<td>
				<input name="cat-tel" id="cat-tel" type="text" value="';
				echo get_option('cat-tel-'.$tag->term_id).'" size="40"/><br>
				<span class="cat-tel">'.$tag->name.' on the phone.</span>
			</td>
		</tr>';
		
	echo '<tr class="form-field">
			<th scope="row"><label for="cat-url">URL</label></th>
			<td>
				<input name="cat-url" id="cat-url" type="text" value="';
				echo get_option('cat-url-'.$tag->term_id).'" size="40"/><br>
				<span class="cat-url">'.$tag->name.' on the URL.</span>
			</td>
		</tr>';	
		
		
}
add_action('category_edit_form_fields','ems_edit_category_field',10,2);

// 保存数据
function ems_taxonomy_metadate($term_id){
	if(isset($_POST['cat-tel']) && isset($_POST['cat-url'])){
		//判断权限--可改
		if(!current_user_can('manage_categories')){
			return $term_id;
		}
		// 电话
		$tel_key = 'cat-tel-'.$term_id; // key 选项名为 cat-tel-1 类型
		$tel_value = $_POST['cat-tel'];	// value
		
		// url
		$url_key = 'cat-url-'.$term_id;
		$url_value = $_POST['cat-url'];	
			
		// 更新选项值
		update_option( $tel_key, $tel_value ); 
		update_option( $url_key, $url_value );
	}
}

// 虽然要两个钩子,但是我们可以两个钩子使用同一个函数
add_action('created_category','ems_taxonomy_metadate',10,1);
add_action('edited_category','ems_taxonomy_metadate',10,1);
?>
添加分类页面:

编辑分类页面:

调用方法

<?php 
	// 取出当前分类 id: $categories[0]->term_id
	$categories = get_the_category();
	$term_id = $categories[0]->term_id;
	$cat_name = $categories[0]->name;	
?>
<div class="phone">
  <div class="p1"><?php echo get_option('cat-tel-'.$term_id);?></div>
  <div class="p2"><a href="<?php echo get_option('cat-url-'.$term_id);?> " target="_blank"><?php echo $cat_name;?></a></div>
</div>




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值