So you want to sort tables on your WordPress site, without learning a whole mess of code.
Good news. There’s a plugin called Table Sorter that can do this and in pretty much just works. Except… There are cases where you’re outputting data in a theme (or a plugin) and you can’t use that plugin to do it.
Don’t panic, we’ve got you.
Enqueue The Right Tablesorter
I’m aware there’s a tablesorter.com
– Don’t use it. It’s out of date at the site is possibly hacked. Instead, grab Tablesorter from RobG (aka mottie). Rob is still updating this plugin and debugging it, so it’s a better bet that the various other forks.
You’ll enqueue this the ‘normal’ way:
wp_enqueue_script( 'tablesorter', plugins_url( 'jquery.tablesorter.js', __FILE__ ), array( 'jquery' ), '2.30.5', false );
There’s a second part to the enqueue though. You see you also need to tell it what to sort. That is, tell the javascript what to pay attention to.
That’s done by using a class and an ID: <table id="myTable" class="tablesorter"></table>
If you’re using the plugin I mentioned above, you only have to do the latter, because it accounts things differently but, properly, you should be using the ID. Then you have to insert this javascript:
$(function() { $("#myTable").tablesorter(); });
Which is actually wrong. For WordPress. Again, no panicking!
jQuery(document).ready(function($){ $("#myTable").tablesorter(); }); </script>
See? That was easy. If you wanted to be more WordPressy, you do this:
wp_add_inline_script( 'tablesorter', 'jQuery(document).ready(function($){ $("#nationsTable").tablesorter(); });' );
You were expecting more?
That’s really it. I do some extra weird stuff, since I call it on one page only (statistics) and that pages uses query variables so you can have /statistics/nations/
without me needing to make multiple sub pages, and it looks like this:
function enqueue_scripts() { if ( is_page( array( 'statistics' ) ) ) { $statistics = get_query_var( 'statistics', 'none' ); wp_enqueue_script( 'tablesorter', plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/jquery.tablesorter.js' , array( 'jquery' ), '2.30.5', false ); wp_enqueue_style( 'tablesorter', plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/theme.bootstrap_4.css' ); switch( $statistics ) { case 'nations': wp_add_inline_script( 'tablesorter', 'jQuery(document).ready(function($){ $("#nationsTable").tablesorter({ theme : "bootstrap", }); });' ); break; case 'stations': wp_add_inline_script( 'tablesorter', 'jQuery(document).ready(function($){ $("#stationsTable").tablesorter({ theme : "bootstrap", }); });' ); break; } } }
Oh right that also demonstrates a theme!
Tablesorter lets you use themes like Bootstrap 4.x so your tables can be all matchy-matchy.
But at this point, it should be enough to get your tables sorted.