【问题标题】:Datatable server side wordpress integration数据表服务器端 wordpress 集成
【发布时间】:2013-01-10 01:33:10
【问题描述】:

所以,我继承了一个基于数据表构建的 Intranet 站点。基本上它是在 Wordpress 中制作的,然后显示用户在数据表中填写的自定义字段。但它在每个帖子中查询 40 列,超过 2k 条目,因此当用户尝试查看表中的数据时,它现在陷入停滞状态。

我正在尝试利用 Datatables 的服务器端方面来解决这个问题,但由于 sql 数据的格式化方式而遇到了一些麻烦。

谁能提供有关如何设置 server_processing.php 文件的任何帮助(我正在使用这个:http://datatables.net/development/server-side/php_mysql)到:

  1. 根据 wp_posts.ID 索引显示行
  2. 根据不同的表 (wp_postmeta) 在此行中显示列,其中每个列值在 wp_postmeta 表中按 1 中找到的 ID 单独索引
  3. 将整行链接到 wp_posts 表中的网址

如果有人有任何想法,我将不胜感激......

【问题讨论】:

标签: wordpress datatables server-side


【解决方案1】:

绝对是 WordPress 的插件是最有效的。 AJAX 可能与使用 WordPress 编辑功能等核心的 JQuery 发生冲突/导致问题。我会去 WordPress.org 并在插件下查找帮助。还有付费/高级 Intranet 插件,例如 Simple Intranet。 :) 克里斯

【讨论】:

    【解决方案2】:

    您可能对这个插件感兴趣 - 看起来它完全符合您的要求:http://wpdatatables.com

    服务器端处理示例:http://wpdatatables.com/display-mysql-table-in-wordpress/

    【讨论】:

      【解决方案3】:

      您肯定需要一个包含 DataTables 功能的 Wordpress 表格插件。您可以考虑使用 Tabulizer for Wordpress (http://www.tabulizer.com),它支持服务器端处理并仅在需要时通过 Ajax 调用加载表数据。还有一个数据源缓存以提高性能。

      【讨论】:

        【解决方案4】:

        WordPress 或 Core PHP 中的 Ajax 数据表或服务器端处理数据表。

        HTML 代码

        <table id="student_table" width="100%">
            <thead>
                <tr>
                    <th>Roll No.</th>
                    <th>Full Name</th>
                    <th>Phone</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
        
            </tbody>
            <tfoot>
                <tr>
                    <th>Roll No.</th>
                    <th>Full Name</th>
                    <th>Phone</th>
                    <th>Action</th>
                </tr>
            </tfoot>
        </table>
        

        jQuery 代码

        jQuery('#student_table').DataTable({
            "bProcessing": true,
            "serverSide": true,
            "ajax":{
                "url": FrontendConfig.ajaxurl+'?action=getStudentsFromExamIdAjax&exam_nounce=exam_nounce_data&exam_id=1',
                type: "post",
            }
        });  
        

        WordPress 或 PHP 代码

        add_action('wp_ajax_getStudentsFromExamIdAjax', 'getStudentsFromExamIdAjax' );
        add_action('wp_ajax_nopriv_getStudentsFromExamIdAjax', 'getStudentsFromExamIdAjax' );
        
        function getStudentsFromExamIdAjax(){
            if(empty($_GET['action']) || empty($_GET['exam_id'])){
                wp_send_json_error( new \WP_Error( 'Bad Request' ) );
            }
        
            if(isset($_GET['exam_id']) && $_SERVER['REQUEST_METHOD'] === 'POST' && wp_verify_nonce( $_GET['exam_nounce'], 'exam_nounce_data' )):
        
                $exam_id = (isset($_GET['exam_id'])) ? absint($_GET['exam_id']) : '';
        
                /*@ You can create a function to get the data here */
                $students = getStudentsFromExamId($exam_id);
        
                $tdata = [];
                foreach ($students as $key => $value):
                    $tdata[$key][] = $value->roll_no;
                    $tdata[$key][] = $value->name;
                    $tdata[$key][] = $value->phone;
                    $tdata[$key][] = 'action here';
                endforeach;
        
                $total_records = count($tdata);
        
                $json_data = array(
        
                    /* $_REQUEST['draw'] comes from the datatable, you can print to ensure that */
        
                    "draw"            => intval( $_REQUEST['draw'] ), 
                    "recordsTotal"    => intval( $total_records ),
                    "recordsFiltered" => intval( $total_records  ),
                    "data"            => $tdata
                );
        
                echo json_encode($json_data);
            endif;
        
            wp_die();
        }
        

        【讨论】:

        【解决方案5】:

        Custom.js

        jQuery( document ).ready(function() {
        alert('test');
         jQuery('#employee_grid').DataTable({
                  "bProcessing": true,
                  "serverSide": true,              
                  "ajax":{
                     url :ajax_url_object.ajax_url+'?action=getStudentsFromExamIdAjax&exam_nounce=exam_nounce_data&exam_id=1', // json datasource
                     type: "POST",  // type of method  ,GET/POST/DELETE
                     error: function(){
                       jQuery("#employee_grid_processing").css("display","none");
                     }
                   }
           });  });
        

        WordPress 或 PHP 代码

        function theme_styles1()
        

        {

        $template_dir_uri =content_url();
        $pluginurl =plugins_url();
        
        //====================js
        wp_enqueue_style( 'vpn-custom-style1','https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css', true );
        
        wp_enqueue_style( 'vpn-custom-boostrap1','https://cdn.datatables.net/1.11.3/css/dataTables.bootstrap4.min.css', true );
        
        wp_enqueue_script( 'vpn-script11','https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js', true );
        wp_enqueue_script( 'vpn-script21','https://cdn.datatables.net/1.11.3/js/dataTables.bootstrap4.min.js', true );
        
        wp_enqueue_script( 'vpn_script31', plugin_dir_url( __FILE__ ).'js/custom.js', true );
        

        //============ ajax url

        $urls= array('ajax_url'=> admin_url( 'admin-ajax.php' ),
                        'site_url' => site_url()
                        );
        wp_localize_script( 'vpn_script31', 'ajax_url_object',$urls);
        

        }

        add_action('wp_enqueue_scripts', 'theme_styles1',99);

        div class="wrap">   
            <h1>Service List</h1>
        <div class="container">
            <table id="employee_grid" class="display" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>Empid</th>
                        <th>Name</th>
                        <th>Salary</th>
                        <th>Age</th>
                    </tr>
                </thead>
        
                <tfoot>
                    <tr>
                        <th>Empid</th>
                        <th>Name</th>
                        <th>Salary</th>
                        <th>Age</th>
                        
                    </tr>
                </tfoot>
            </table>
        </div>
        

        add_action('wp_ajax_getStudentsFromExamIdAjax', 'getStudentsFromExamIdAjax' ); add_action('wp_ajax_nopriv_getStudentsFromExamIdAjax', 'getStudentsFromExamIdAjax');

        函数 getStudentsFromExamIdAjax(){

        global $wp;
        
        $servername = "localhost:3308";
        $username = "root";
        $password = "";
        $dbname = "demo";
        
        $conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
        $params = $columns = $totalRecords = $data = array();
        
        $params = $_REQUEST;
        // echo "<pre>";
        // print_r($params);
        // die;
        
        //define index of column
        $columns = array( 
            0 =>'id',
            1 =>'employee_name', 
            2 => 'employee_salary',
            3 => 'employee_age'
        );
        
        $where = $sqlTot = $sqlRec = "";
        
        // check search value exist
        if( !empty($params['search']['value']) ) {   
            $where .=" WHERE ";
            $where .=" ( employee_name LIKE '".$params['search']['value']."%' ";    
            $where .=" OR employee_salary LIKE '".$params['search']['value']."%' ";
        
            $where .=" OR employee_age LIKE '".$params['search']['value']."%' )";
        }
        
        // getting total number records without any search
        $sql = "SELECT * FROM `employee` ";
        $sqlTot .= $sql;
        $sqlRec .= $sql;
        //concatenate search sql if value exist
        if(isset($where) && $where != '') {
        
            $sqlTot .= $where;
            $sqlRec .= $where;
        }
        
        
        $sqlRec .=  " ORDER BY ". $columns[$params['order'][0]['column']]."   ".$params['order'][0]['dir']."  LIMIT ".$params['start']." ,".$params['length']." ";
        
        $queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
        
        
        $totalRecords = mysqli_num_rows($queryTot);
        
        $queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");
        
        //iterate on results row and create new index array of data
        while( $row = mysqli_fetch_row($queryRecords) ) { 
            $data[] = $row;
        }   
        
        // echo "<pre>";
        // print_r($data);
        // die;
        
        $json_data = array(
                "draw"            => intval( $params['draw'] ),   
                "recordsTotal"    => intval( $totalRecords ),  
                "recordsFiltered" => intval($totalRecords),
                "data"            => $data   // total data array
                );
        
        echo json_encode($json_data);  // send data as json format
           
        

        }

        【讨论】:

        • 我使用了上面的代码但是没有在数据表中赋值。你能帮忙吗?
        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 2014-09-06
        • 1970-01-01
        • 1970-01-01
        • 2018-04-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-18
        • 2015-04-27
        • 2014-10-06
        相关资源
        最近更新 更多