如何在worpdress中的用户部分中按自定义列进行排序

时间:2016-02-08 05:54:06

标签: php wordpress

我在用户部分有2个自定义栏,按“商店名称”和“日期”这两个保存在DB中的users_meta表中,如何在用户管理列表中显示按“商店名称”排序的数据,然后按“日期”。到目前为止我的当前代码添加列标题并从用户部分的user_meta中获取它们如下。

主题Function.php

/* Adds a store name and date column to the user display dashboard.
*
* @param    $columns    The array of columns that are displayed on the user dashboard
* @return           The updated array of columns now including zip codes.
*/
function theme_add_user_Store_name_column( $columns ) {

 $columns['Store_name'] = __( 'Store name', 'theme' );
 $columns['DATE'] = __( 'Date', 'theme' );
 return $columns;

 } // end theme_add_user_Store_name_column
 add_filter( 'manage_users_columns', 'theme_add_user_Store_name_column' );
 /**
* Populates the store name and date column with the specified user's store name.
*
* @param    $value      An empty string
* @param    $column_name    The name of the column to populate
* @param    $user_id    The ID of the user for which we're working with
* @return           The store name associated with the user
*/
function theme_show_user_Store_name_data( $value, $column_name, $user_id )   {

 if( 'Store_name' == $column_name ) {
     return get_user_meta( $user_id, 'Store_name', true );
 }

 if( 'DATE' == $column_name ) {
    return get_user_meta( $user_id, 'DATE', true );
 }// end if

 }  
 // end theme_show_user_Store_name_data
 add_action( 'manage_users_custom_column', 'theme_show_user_Store_name_data', 10, 3 );

2 个答案:

答案 0 :(得分:0)

使用以下代码根据自定义元字段对users表进行排序,这用于单列,您可以修改它以添加第二个字段。

// Register the column as sortable    
 function Store_name_column_register_sortable( $columns ) {
   $columns['Store_name'] = 'Store_name';
   return $columns;
  }

add_filter( 'manage_users_sortable_columns', 'Store_name_column_register_sortable' );
function Store_name_column_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'Store_name' == $vars['orderby'] ) {
    $vars = array_merge( $vars, array(
    'meta_key' => 'Store_name',
    'orderby' => 'meta_value'
   ) );
 }
 return $vars;
}
add_filter( 'request', 'Store_name_column_orderby' );

答案 1 :(得分:0)

要扩展PHPExpert的答案,从Wordpress 4.4开始,您可以使用users_list_table_query_args代替request

// Register the column as sortable    
function Store_name_column_register_sortable( $columns ) {
    $columns['Store_name'] = 'Store_name';
    return $columns;
}
add_filter( 'manage_users_sortable_columns', 'Store_name_column_register_sortable' );

function Store_name_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'Store_name' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => 'Store_name',
            'orderby' => 'meta_value'
        ) );
    }
    return $vars;
}
add_filter( 'users_list_table_query_args', 'Store_name_column_orderby', 10, 1 );