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

I have a custom post type called laptop with custom fields such as CPU, OS, RAM etc. creatied using the Advanced Custom Fields plugin.

I’m displaying a table of laptops, where the table header is a row of custom fields, and each following row is a laptop name and it’s custom field values in each of the corresponding column cells.

I want to be able to sort the table by clicking on the table TH cell containing the custom field name.

I’ve been pointed to meta query clauses by ACF support, but I’m out of my depth with those.

I’d really appreciate some help in generating URLs to wrap around the the custom field name in each TH element.

2 Answers
2

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