PHP, MySQL, JavaScript, Windows 7, Linux
jQuery Tablesorter helper function for WordPress
In one of my projects, I converted WordPress into a reporting engine, which is used at 20 car dealerships to track Internet sales. During development, I found that I was writing the same code over and over again for the jQuery Tablesorter plugin, which allows you to sort tables using a simple JavaScript call.
First, I would have to queue the script file, then add the appropriate JavaScript. To ensure the JavaScript was executed at the right time, I had to create a function to use it with add_action(). I found this to be tedious and unnecessary, and wrote a simple helper function to remedy this. The following function was added to /wp-admin/includes/template.php, but if you use it, it will most likely go in a plugin or theme include. This will prevent it from being overwritten during WordPress upgrades.
/**
* Make all tables with the specified identifier sortable using the jQuery Tablesorter plugin.
*
* @uses wp_enqueue_script() To enqueue the jQuery Tablesorter script.
*
* @param string $identifier jQuery selector (.sortable, #element_id, table, etc.)
* @param array $args Default is empty string. Array of arguments to pass to $.tablesorter()
* @return void
*/
function make_table_sortable($identifier, $args = '') {
global $sortable_tables;
if ( in_array($identifier, (array)$sortable_tables) )
return;
wp_enqueue_script('jquery-tablesorter');
$sortable_tables[] = array(
'identifier' => $identifier,
'args' => $args
);
add_action('admin_print_footer_scripts', '_make_table_sortable');
}
function _make_table_sortable() {
global $sortable_tables;
if ( count( (array)$sortable_tables ) <= 0 )
return;
?>
<script type="text/javascript">
<?php
foreach ($sortable_tables as $sortable_table) {
if ( !is_array($sortable_table['args']) ) {
$arguments = '';
} else {
$arguments = '{';
$args_count = sizeof($sortable_table['args']);
$i = 0;
foreach ($sortable_table['args'] as $k => $v) {
$arguments .= $k . ': ' . $v;
if (++$i != $args_count) $arguments .= ', ';
}
$arguments .= '}';
}
?>
$('<?php echo esc_js($sortable_table['identifier']); ?>').tablesorter(<?php echo esc_js($arguments); ?>);
<?php } ?>
</script>
<?php
}
Below exemplifies usage of the make_table_sortable() function:
// Sort tables with class 'sortable', first and second columns in ascending order with first taking precedence.
make_table_sortable('.sortable', array('sortList' => '[[0,0], [1,0]]'));
// Sort table with ID 'sortable', first column in ascending order. Turn debugging on.
make_table_sortable('#sortable', array('sortList' => '[[1,0]]', 'debug' => 'true'));