1

所以,我继承了一个基于数据表构建的 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 表中的 url

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

4

5 回答 5

1

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

于 2013-01-29T22:46:39.170 回答
0

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

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

于 2014-03-09T19:42:42.653 回答
0

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

于 2014-05-09T10:47:56.497 回答
0

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();
}
于 2019-10-16T18:33:01.897 回答
-1

自定义.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
   

}

于 2021-12-30T11:37:00.933 回答