对于喜欢玩WordPress开发的小伙伴当然喜欢对WordPress进行无限的折腾,怎么高大尚怎么来,反正人不死折腾不休。我也经常被圈里的朋友问个没完没了,好朋友说谈付费有点伤感情不谈钱但又要喝西北风了。好今天心情不错给大家分享个WordPress后台用户与文章列排序教程,以往度娘上都是对于时间的排序,对于喜欢开发搞字段排序的教程一个木有。


//文章排序
add_filter('pre_get_posts', 'custom_column_orderby');
function custom_column_orderby($query) {
	if (!is_admin() || !$query->is_main_query()) {
		return;
	}
	if ($query->query_vars['post_type'] == 'custom_post_type' && ($orderby = $query->get('orderby'))) {
		switch ($orderby) {
			case 'custom_field':
				$query->set('meta_key', 'custom_field');
				$query->set('orderby', 'meta_value_num');
				break;
			default:
				break;
		}
	}
}
add_filter( 'manage_users_sortable_columns', 'mytheme_user_sortable_columns' );
//改变后台用户注册排序A
add_filter('manage_users_columns','ruike_add_users_column_reg_time');
function ruike_add_users_column_reg_time($column_headers){
	$column_headers['reg_time']= '注册时间';
	$column_headers['reg_key'] = '验证状态';
	return $column_headers;
}
add_filter('manage_users_custom_column', 'ruike_show_users_column_reg_time',10,3);
function ruike_show_users_column_reg_time($value, $column_name, $user_id){
	if($column_name=='reg_time'){
		$user = get_userdata($user_id);
		return get_date_from_gmt($user->user_registered);
	}else if($column_name=='reg_key'){
		$user = get_userdata($user_id);
		return ($user->activation_key=="success")?'已验证':'未验证';
	}
	return $value;
}
add_filter( "manage_users_sortable_columns", 'ruike_users_sortable_columns' );
function ruike_users_sortable_columns($sortable_columns){
	$sortable_columns['reg_time']='regtime';
	$sortable_columns['reg_key'] ='regkey';
	return $sortable_columns;
}
add_action('pre_user_query', 'ruike_user_column_orderby');
function ruike_user_column_orderby($user_search) {
    global $wpdb, $current_screen;
 
	if (isset($current_screen->id) && 'users' != $current_screen->id) {
	    return;
	}
 
    $vars = $user_search->query_vars;
 
    if('regkey' == $vars['orderby']) {
        $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON {$wpdb->users}.ID=m1.user_id AND (m1.meta_key='activation_key')";
        $user_search->query_orderby = ' ORDER BY UPPER(m1.meta_value) '. $vars['order'];
    } elseif ('regtime' == $vars['orderby']) {
        $user_search->query_orderby = ' ORDER BY user_registered ' .$vars['order'];
   	}
}

本次教程用户代码区为瑞课现用代码还希望尊重版权,适当的修改成您自己定义的名称。