Sometimes you just need a big list of data.

It’s not the most glamorous kind of web development, but we’re often asked to build user interfaces for viewing or working with data stored in a WordPress site.

There are countless ways you can do this, but recently a couple of projects have reintroduced me to a simple and effective approach: jQuery DataTables

This venerable plugin goes all the way back to 2008, but is still being actively developed and offers a lot of features with relatively little code.

It also has good documentation, heaps of examples and a large userbase which makes it easier to find help with any issues you encounter.

Here’s my quick how-to for getting up and running with DataTables on WordPress.

Step 1. Get the jQuery DataTables assets onto your page

Let’s do this the proper way, in your functions.php

Nothing fancy there, just enqueuing the JavaScript and CSS files, and telling WordPress to load jQuery before the DataTables plugin.

Step 2. Add the basic table structure

You don’t need much HTML for the table – the rows and columns will come from the plugin, so just add the basic structure and column headers.

This example has some extra PHP because it’s a custom WordPress page template, but the (minimal) HTML is the important bit.

Step 3. Create a data source

Now we need some data for our table. I am going to let DataTables handle all the filtering and searching, so WordPress just needs to give me all the data it has in JSON format.

The WordPress JSON API is a possibility for this, but it has certain limitations such as the number of posts you can get in one request.

For the purposes of this example, I will add a simple AJAX endpoint so I have complete control over what it does.

It will get all published posts and send them back in the format expected by DataTables, along with a count of how many posts were found:

The upshot of this is that we (and DataTables) can hit the following URL and see our JSON-encoded posts: /wp-admin/admin-ajax.php?action=datatables_endpoint

4. Set up the DataTable

Now we just need a bit of JavaScript to set up the table and we will be in business.

Add this to your theme JS file (or even better, a dedicated JS file for your DataTable feature):

The documentation will explain these options better than I can, but the key points are specifying our ajax endpoint, and the columns we want in our table.

DataTables expects an array of result objects in the ‘data’ property of the response, which is exactly what we prepared earlier.

Our simple column mapping tells DataTables that the first column value comes from the ‘ID’ of a result object, while the second column value is the ‘post_title’.

Conclusion

That’s about it for my simple ‘hello world’ DataTable. There are lots of powerful options available to filter and search the table, and the sister plugin jQuery DataTables Editor lets you easily set up a full editing interface for your data – but that is a post for another time!