How to sort a table of custom posts by column containing custom field

To follow up on @rock3t’s comment, do you really have to query the backend whenever a user clicks on a column header?

Have you looking into using the jQuery tablesorter? It allows an end-user to sort an HTML table by doing DOM manipulations.

I’ve never used it in a WP project, but I have used it extensively in other projects I’ve built and it works great. It’s very configurable, so I’m sure it will satisfy your needs.

tablesorter is not one of the jQuery plugins included with WP Core. So you’ll have to download it (from the above link), include it in your plugin/theme somewhere and enqueue it. Then, enqueue a simple JS file that would like something like:

(function ($) {
    $(document).ready (function () {         
        $('#id_of_your_table').tablesorter ({widgets: ['zebra']}) ;     
        }) ;
})(jQuery) ;

You can read more about how to use tablesort in their docs, including various other parms to the tablesorter() method.

Leave a Comment