• 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
    • MLIS Class Projects (2019-2022)
    • Portfolio (2002-2019)
    • Services
    • WordPress Plugins
    • WordPress Themes
    • Presentations and Interviews
    • on GitHub →

Stephanie Leary

Writer, WordPress consultant, recent MLIS grad

  • 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

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 © 2023 Stephanie Leary · Contact