• Skip to primary navigation
  • Skip to main content
  • Skip to footer
  • Books
    • Content Strategy for WordPress (2015)
    • WordPress for Web Developers (2013)
    • Beginning WordPress 3 (2010)
  • Blog
    • Content Modeling for WordPress
    • WordPress Hidden Gems
    • Web Design
  • Work
    • Presentations and Interviews
    • on GitHub →
    • MLIS Class Projects (2019-2022)
    • Portfolio (2002-2019)
    • WordPress Plugins

Stephanie Leary

Writer, Front End Developer, former WordPress consultant

  • About
    • Press Kit
    • Presentations and Interviews
  • Contact Me

Add sortable, striped table script — only when needed

January 21, 2010 Stephanie Leary 2 Comments

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).

WordPress javascript, tables, Templates

This is an excerpt from Content Strategy for WordPress.My latest books are Content Strategy for WordPress (2015) and WordPress for Web Developers (2013). Sign up to be notified when I have a new book for you.

Reader Interactions

Comments

  1. Joe Van Steen says

    August 3, 2011 at 10:36 am

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

    Reply
    • Stephanie says

      August 8, 2011 at 9:45 am

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

      if (stripos($post-&gt;post_content, '&lt;table')) {
      
      Reply

Leave a Reply Cancel reply

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

Footer

My Books

I’m a front end developer at Equinox OLI, working on open source library software. I was previously a freelance WordPress developer in higher education. You can get in touch here or on LinkedIn.

Copyright © 2025 Stephanie Leary · Contact