I’ve started using wpDataTables for data driven tables in WordPress. The ability to have a table linked to an Excel spreadsheet is neat and the automagically formatted tables that use the jQuery Data Tables plugin are nice too. I needed to tweak few things though. First, center align the table titles. Easy enough using the wpdatatables_filter_rendered_table
add_filter('wpdatatables_filter_rendered_table','my_filter_rendered_table'); function my_filter_rendered_table( $table_content, $table_id ) { $content=$table_content; $content=str_replace('<h2>','<h2 style="text-align:center;">',$content); return $content; }
The second issue I was having was with URL Link Columns. These are driven from an Excel spreadsheet by separating the URL and the link text with two pipe (|) characters. Something like:
http://someniftysite.com||Nifty Link Text
In the case of the data I was displaying some of the cells would need links and some wouldn’t. Trouble was wpDataTables appears to render every value in a URL Link Column as a link whether you pass it a URL or not. In fact, it uses the Link Text as the URL if you omit the URL. Instant broken links, yuck. No problems, I thought initially, I’d just use the provided wpdatatables_filter_link_cell filter to grab the URL links, parse out the URL and the link text and just return the link text if the URL was invalid. Pretty easily done with a bit of regex like:
$url=preg_match('/href="(.*?)"/', $link, $url_matches); $link_text=preg_match('/>(.*?)<\/a>/', $content, $link_text_match);
It worked beautifully for the Link Text but rather frustratingly preg_match stubbornly returned 0 (no match) for the URL no matter what I tried. Even when I VAR_DUMP’ed the link it appeared that the preg_match should work. But it didn’t. In the end I used substr to echo back the link one character at a time and hey presto, wpDataTables was wrapping the href parameter in a single quote rather than a double quote. When I echoed the value to output using VAR_DUMP the browser (un)helpfully replaced the single quotes with double quotes. Grrrr. Anyway here’s the code that worked:
add_filter('wpdatatables_filter_link_cell','my_filter_link_cells'); function my_filter_link_cells($link) { $content=$link; $url=preg_match("/href='(.*?)'/", $link, $url_matches); $link_text=preg_match('/>(.*?)<\/a>/', $content, $link_text_match); if (strpos($url_matches[1],"/")===false || strpos($url_matches[1]," ")!==false) { $content=$link_text_match[1]; } return $content; }
Now my tables displayed links for values that actually had a proper URL and just text for those that didn’t. Yay.
wpDataTables seems pretty good, it isn’t free but $29 seems like a decent price for something that has worked pretty much exactly as advertised and has a tonne of features. Recommended.