I have a code in which I want to display tables with datatables script.

function viewBooks_admin(){

?>
<div class="wrap">
<h4>Books List</h4>

<table id="widefat" class="widefat">
    <thead>
        <tr>
            <th>Book Name</th>
            <th>Book Description</th>
            <th>Author Name</th>
            <th>Book Price</th>
            <th>Book Image</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Book Name</th>
            <th>Book Description</th>
            <th>Author Name</th>
            <th>Book Price</th>
            <th>Book Image</th>
        </tr>
    </tfoot>
    <tbody>
        <?php
            global $wpdb;
            $mytestdrafts=$wpdb->get_results(
                "
                SELECT *
                from ".$wpdb->prefix."books
                "
            );
        ?>
        <?php
            foreach($mytestdrafts as $mytestdraft)
            {
        ?>
                <tr>
                    <?php
                        echo"<td>".$mytestdraft->bookName."</td>";
                        echo"<td>".$mytestdraft->bookDescription."</td>";
                        echo"<td>".$mytestdraft->authourName."</td>";
                        echo"<td>".$mytestdraft->bookPrice."</td>";
                        echo"<td><img src='".$mytestdraft->imageURL."' width='80' height='80'></td>";
                        //echo "<td><a class='btn button-danger' href=''>"
                    ?>
                </tr>
                <?php
            }
        ?>
    </tbody>
</table>
<br><br>

</div>
<?php

}

Add adding this css and javascript

function your_css_and_js() {

        //register style 
        wp_register_style('datatable_css', plugins_url('css/jquery.dataTables.css',__FILE__ ));
        wp_enqueue_style('datatable_css');

        ////register scripts
        wp_register_script( 'jquery-dataTables', plugins_url('js/jquery.dataTables.min.js',__FILE__ ), array('jquery'), true);
        wp_enqueue_script('jquery-dataTables');

        wp_register_script( 'custom', plugins_url('js/custom.js',__FILE__ ), array('jquery'), true);
        wp_enqueue_script('custom');

    }

    add_action( 'admin_enqueue_scripts','your_css_and_js');

Custom.js file

$( document ).ready(function() {
    console.log('dfdfd');
    $("#widefat").dataTable();
 })

The page is loading scripts but datatables are not visible . Don’t know why.
Followed this tutorial for datatables though working file in html https://www.bmthrive.com/datatables-jquery-plugin/

Read more here: Script not working in wordpress admin


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: