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