数据表中的WordPress用户具有短路,搜索和分页功能

时间:2018-09-18 09:24:35

标签: php mysql wordpress datatable

我正在制作一个插件来显示DataTables中的所有用户信息,但是我无法实现Search,filter和Pagination。我大约有 2万个用户。请帮助我。

可能是我需要更改查询以加入wp_userswp_usermeta并获得针对我的案例的结果。我提出了一个问题here和一个类似的tutorial here。我不太擅长编写MySQL查询。请帮我解决一下这个。

我收到类似

的ajax响应
{
  "draw": 1,
  "recordsTotal": 1,
  "recordsFiltered": 1,
  "data": [
    [
      "example@mail.com",
      "Some Name",
      "",
      "admin",
      ""
    ]
  ]
}

这是我的表格结构

 <table id="user_table" class="display table table-striped table-bordered dataTable" style="width:100%">
        <thead class="user-table">
            <tr>
            <th>Email</th>
            <th>Name </th>
            <th>Url</th>
            <th>nickname</th>
            <th>description</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

我的脚本

jQuery(document).ready(function($){
    $(window).on('load', function () {
      setTimeout(loadtable, 200);
    });
    function loadtable(){
        var ajaxurl =  USERAjax.wpajaxusersearch;
        var dataTable = $('#user_table').DataTable({  
           "processing":true,  
           "serverSide": true,  
           "order":[],  
           "pageLength": 10,
           "ajax":{  
                url: ajaxurl,  
                type:"POST"         
           },   
      });
    }
});

还添加了

之类的本地化脚本
function users_assets_scripts(){

    wp_register_script( 'jquery_datatables_js',  plugins_url( 'asset/js/datatables.min.js' , __FILE__ ), array(),null,true );
    wp_enqueue_script( 'jquery_datatables_js' );

    wp_register_style( 'jquery_datatables_css',  plugins_url( 'asset/css/datatables.min.css' , __FILE__ ));
    wp_enqueue_style( 'jquery_datatables_css' );

    wp_localize_script( 'jquery', 'USERAjax', array('wpajaxusersearch' => admin_url( 'admin-ajax.php?action=wpajaxusersearch' )) );
}

add_action('wp_enqueue_scripts', 'users_assets_scripts');

和带有ajax响应的数据获取功能

<?php 
function wpajaxusersearch(){ 

    $request=$_REQUEST;

    global $wpdb;
    $sort= "user_registered";

    //Build the custom database query to fetch all user IDs
    $all_users_id = $wpdb->get_results("SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY $sort ASC LIMIT ".$request['start'].",".$request['length']." " );

    $totalData=$wpdb->num_rows;

    $data=array();
    foreach ( $all_users_id as $i_users_id ) {

            $user = get_userdata( $i_users_id->ID);

            $email              =$user->user_email;
            $user_fullname      =$user->first_name . ' ' . $user->last_name;
            $user_url           =$user->user_url;
            $user_nickname      =$user->nickname;
            $user_profile       =$user->description;
                $sub_array = array();  
                    $sub_array[] = $email;  
                    $sub_array[] = $user_fullname;  
                    $sub_array[] = $user_url;  
                    $sub_array[] = $user_nickname;   
                    $sub_array[] = $user_profile;    
               $data[] = $sub_array; 
    }

    $json_data=array(
        "draw"              =>  (isset($request["draw"]) ? $request["draw"] : 0),  
        "recordsTotal"      =>  intval($totalData),
        "recordsFiltered"   =>  intval($totalData),
        "data"              =>  $data
    );

    echo json_encode($json_data);
    wp_die(); //to remove that 0 response
}
add_action( 'wp_ajax_wpajaxusersearch', 'wpajaxusersearch' );
add_action( 'wp_ajax_nopriv_wpajaxusersearch', 'wpajaxusersearch' );

1 个答案:

答案 0 :(得分:3)

将它们添加到主题的“ functions.php”中,一切就可以了。

// change user query to treat meta result as OR part
add_action( 'pre_user_query', 'user_meta_OR_search');
function user_meta_OR_search($q){   
    if ($search = $q->get('_meta_or_search')){
        add_filter( 'get_meta_sql', function( $sql ) use ( $search ){
            global $wpdb;

            // run once
            static $nr = 0; 
            if( 0 != $nr++ ) return $sql;

            // modify WHERE
            $where = sprintf(
                " AND ( %s OR %s OR %s ) ",
                $wpdb->prepare( "{$wpdb->users}.user_email like '%%%s%%'", $search),
                $wpdb->prepare( "{$wpdb->users}.user_url like '%%%s%%'", $search),
                mb_substr( $sql['where'], 5, mb_strlen( $sql['where'] ) )
            );

            $sql['where'] = $where;

            return $sql;
        });
    }
}

function wpajaxusersearch()
{               
    $request = $_REQUEST;
    $columns = array('user_email','first_name','user_url','nickname','description');
    $search = esc_attr( trim( $request['search']['value'] ) );

    $args = array();
    $limit_args = array( 'number' => $request['length'], 'offset' => $request['start'] );   
    $order_args = array();
    $search_args = array();

    if ( isset($request['order']) && count($request['order']) )     
    {
        $sort_column = $request['order'][0]['column'];          
        $sort_column_name = $columns[$sort_column];
        $sort_dir = $request['order'][0]['dir'];

        if( stristr( $sort_column_name,'user_' ))
            $order_args = array( 'orderby' => $sort_column_name, 'order' => $sort_dir );                
        else
            $order_args = array( 'meta_key' => $sort_column_name, 'orderby' => 'meta_value', 'order' => $sort_dir );
    }
    else
        $order_args = array( 'orderby' => 'user_registered', 'order' => 'ASC' );

    $args = $order_args;

    if(isset($search) && $search != "") 
    {
        $search_args = array(               
            '_meta_or_search' => "*{$search}*",    
            'meta_query' => array(
                'relation' => 'OR',
                array(
                    'key'     => 'first_name',
                    'value'   => $search,
                    'compare' => 'LIKE'
                ),
                array(
                    'key'     => 'last_name',
                    'value'   => $search,
                    'compare' => 'LIKE'
                ),
                array(
                    'key'     => 'nickname',
                    'value'   => $search,
                    'compare' => 'LIKE'
                ),
                array(
                    'key'     => 'description',
                    'value'   => $search,
                    'compare' => 'LIKE'
                )
            )
        );                          
    }       

    $all_users = new WP_User_Query( $args );
    $total_users = count($all_users->get_results());
    $filtered_users = count($all_users->get_results());

    if(isset($search) && $search != "") 
    {
        $args = array_merge($args, $search_args);
        $all_users = new WP_User_Query( $args );
        $filtered_users = count($all_users->get_results());
    }

    $args = array_merge($args, $limit_args);
    $all_users = new WP_User_Query( $args );        

    foreach ( $all_users->get_results() as $user ) {
        $email = $user->user_email;
        $user_fullname = $user->first_name . ' ' . $user->last_name;
        $user_url = $user->user_url;
        $user_nickname = $user->nickname;
        $user_profile = $user->description;
        $sub_data = array();  
        $sub_data[] = $email;  
        $sub_data[] = $user_fullname;  
        $sub_data[] = $user_url;  
        $sub_data[] = $user_nickname;   
        $sub_data[] = $user_profile;    
        $data[] = $sub_data; 
    }

    $json_data=array(
        "draw"              =>  (isset($request["draw"]) ? $request["draw"] : 0),  
        "recordsTotal"      =>  intval($total_users),
        "recordsFiltered"   =>  intval($filtered_users),
        "data"              =>  $data
    );

    echo json_encode($json_data);
    wp_die();
}
add_action( 'wp_ajax_wpajaxusersearch', 'wpajaxusersearch' );
add_action( 'wp_ajax_nopriv_wpajaxusersearch', 'wpajaxusersearch' );