有时候,我们需要通过分类的序号来排序分类列表,wordpress的分类有个term_order属性,默认为0。
<?php
function mbt_add_category_field(){
echo '<div class="form-field">
<label for="cat-num">序号</label>
<input name="_term_order" id="cat-num" type="text" value="" size="40">
<p>专题列表排序,数字越好,越靠前</p>
</div>';
}
add_action('category_add_form_fields','mbt_add_category_field',10,2);
// 分类编辑字段
function mbt_edit_category_field($tag){
echo '<tr class="form-field">
<th scope="row"><label for="cat-num">排序</label></th>
<td>
<input name="_term_order" id="cat-num" type="text" value="';
echo ( ! empty( $tag->term_group ) ) ? $tag->term_group : '0';
echo '" size="40"/><br>
<span class="cat-num">'.$tag->name.' 的专题排序</span>
</td>
</tr>';
}
add_action('category_edit_form_fields','mbt_edit_category_field',10,2);
// 保存数据
function mbt_taxonomy_metadate($term_id){
global $wpdb;
if( isset( $_POST['_term_order'] ) ) {$wpdb->update( $wpdb->terms,array('term_group' => $_POST['_term_order']),array( 'term_id'=> $term_id));}
}
// 虽然要两个钩子,但是我们可以两个钩子使用同一个函数
add_action('created_category','mbt_taxonomy_metadate',10,1);
add_action('edited_category','mbt_taxonomy_metadate',10,1);
?>
使用方法:
<?php $catid = $options['topiccatid']; $args=array( 'child_of'=>$catid, 'orderby' => 'term_group', 'order'=>'ASC', 'hide_empty' => 0, ); $categories=get_categories($args); ?>


0 个评论