.
WORDPRESS PLUGINS ABOUT

Installing DataTables for a WordPress Plugin

2 minute read, 1 if you're quick

A quick post about adding/using Datatables in the Admin - backend - section of WordPress in your Theme or Plugin.
WordPress loads jQuery automatically - it uses it - so you don't need to. When you download DataTables jQuery is either linked to or is a file as part of the download.
Using another version of jQuery at the same time as the default already loaded version by WordPress will not only slow your site down but if you submit a plugin with this to their repo it will not be allowed.

So how do we fix it?

Loading jQuery: wp_enqueue_script not working

Remove the link to the jQuery file, it is not needed. It looks like this:

<script src='jquery-3-6-0.min.js?ver=6.2' id='JG-jquery-js'></script>

You will now need to enqueue your JavaScript file using a command like this one:

function my_plugin_enqueue_scripts() {
    // Enqueue jQuery (it will only be added once, even if other themes or plugins enqueue it too)
    wp_enqueue_script('jquery');
    
    // Enqueue your own scripts (assuming your script is located in a file called 'my-plugin-script.js' within your plugin directory)
    wp_enqueue_script('my-plugin-script', plugin_dir_url(__FILE__) . 'my-plugin-script.js', array('jquery'), '1.0', true);
}

// Hook into WordPress
add_action('wp_enqueue_scripts', 'my_plugin_enqueue_scripts');

The most up-to-date version of WordPress will not need the wp_enqueue_script('jquery'); command, however, if an older version of WordPress is used - say a customer's site - then it is recommended to add the line. It will only load jQuery once if not loaded, so will not slow your site down.

In the DataTables docs and files you will need to use option commands in a script, something like this:

<script>
	$(document).ready( function () {
		$('#id').DataTable( {
		
			"order": [[ 0, 'desc' ], [ 1, 'desc' ]]
		
		} );
	} );
</script>

WordPress loads jQuery in "No Conflict" mode, which means that the $ shortcut is not available, and you have to use jQuery instead:

jQuery(document).ready(function($) {
  // Your code here.
});

This is important and will stop the tables from working if not updated.

Hope that helps!

Stuart

^