很多使用 WordPress 程序建网站的同学都苦于 WP 程序的分类目录的属性太少了,只有分类的标题,别名,描述。不能像文章模板里可以调用 wordpress 自定义栏目,而分类目录下的其它属性却很难自定义。
为了让我们更好的利用 wordpress 程序做出需要的网站功能效果,分享一下如何给分类目录添加自定义的 META 属性。
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);
- ?>
3、调用方法(可以在 wordpress 文章模板(single.php)调用分类的 META 信息)
- <?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>
以上是通过代码的方式给我们的分类目录添加 META 属性字段,我们还可以使用插件的方法来完成同样的效果。
- 1、本站大部分内容均收集于网络,若内容侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn,我们将第一时间处理!
- 2、本站资源所需价格并非资源售卖价格,是收集、整理、编辑以及本站运营的适当补贴,并且本站不提供任何免费技术服务。
- 3、所有资源仅限参考和学习,版权归原作者所有,更多请阅读无言说网络服务器协议。