DataTables dataTables_wrapper is not loading

Viewed 1405

In my WordPress v5.5.1, I have a custom post type archive page to show all the posts. For this feature, we wanted to use the DataTable. Have enqueued the DataTable files as below:

wp_deregister_script('jquery'); // deregistered default jQuery
wp_enqueue_script('jq', 'https://code.jquery.com/jquery-3.5.1.min.js', array(), null, true); // for Bootstrap
// DATATABLES
wp_enqueue_script('js', 'https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js', array('jq'), null, true);
wp_enqueue_script('wp-js', get_template_directory_uri() . '/js/scripts.js', array('jq'), null, true);
wp_enqueue_style('css', 'https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css');

In my scripts.js file which is being loaded, I have enabled the DataTables as below:

$(document).ready(function () {
    $('#songs').DataTable();
});

Below is the HTML table:

<table id="songs" class="table dataTable">
    <thead>
        <tr>
            <th>Songs</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Song 1</td>
        </tr>
        <tr>
            <td>Song 2</td>
        </tr>
        <tr>
            <td>Song 3</td>
        </tr>
        <tr>
            <td>Song 4</td>
        </tr>
    <tbody>
</table>

DataTable css files and js files are being loaded and styles are applied.

However the dataTables_wrapper is not being loaded, where we can sort the table content, pagination and search bar. I see only the plain HTML table.

I ran this code in the JSFiddle and works fine (https://jsfiddle.net/0burvh1y/).

I have tried deactivating all plugins and using default WordPress jquery as well, but with no luck.

2 Answers

I have used the below dataTable CDN URLs and DataTables dataTables_wrapper is loading now:

wp_enqueue_script('js', 'https://cdn.datatables.net/v/bs4/dt-1.10.22/datatables.min.js', array('jq'), null, true);
wp_enqueue_style('css', 'https://cdn.datatables.net/v/bs4/dt-1.10.22/datatables.min.css');

Personally, I would create functions and link them to actions like the following :

function add_datatables_scripts() {
  wp_register_script('datatables', 'https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js', array('jquery'), true);
  wp_enqueue_script('datatables');

  wp_register_script('datatables_bootstrap', 'https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js', array('jquery'), true);
  wp_enqueue_script('datatables_bootstrap');
}
 
function add_datatables_style() {
  wp_register_style('bootstrap_style', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
  wp_enqueue_style('bootstrap_style');

  wp_register_style('datatables_style', 'https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css');
  wp_enqueue_style('datatables_style');
}

add_action('wp_enqueue_scripts', 'add_datatables_scripts');
add_action('wp_enqueue_scripts', 'add_datatables_style');
Related