Sillybean

Add sortable, striped table script — only when needed

Ever wondered how I dressed up the tables on this site? I’ll show you! We’ll use the code for adding stylesheets and scripts conditionally to include Yoast’s improved sortable.js only when a post or page contains a table.

// enqueue sortable.js on pages containing tables
function add_sortable ($posts) {
	if (empty($posts)) return $posts;
	$found = false;
	foreach ($posts as $post) {
		if (stripos($post->post_content, '<table')) {
			$found = true;
			break;
		}
	}
	if ($found) {
		wp_enqueue_script('sortable', get_bloginfo('template_url').'/js/sortable.js');
	}
	return $posts;
}
add_filter('the_posts', 'add_sortable');

Add this to your functions.php file. Then add class="sortable" and a unique ID to your tables and view your post or page. If it worked, your table headings should be clickable, and your table rows should be alternating colors (assuming your stylesheet includes .odd and/or .even classes).

Posted on January 21, 2010 at 5:23 pm in WordPress · 2 comments

Sharing this post? The short URL is: http://sillybean.net/?p=2713

2 Responses to “Add sortable, striped table script — only when needed”

  1. Joe Van Steen says:

    Stephanie,
    Line 6 is missing some code for the stripos statement.

    • Stephanie says:

      Thanks. WordPress really did not like that line, but I think I’ve fixed it. It should be:

      if (stripos($post->post_content, '<table')) {
      

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>