Conditionally Adding Scripts

The wp_enqueue_scripts() function will add your script to every page on your site. What if it's a large script and you want to include it only if a shortcode or some other text is present in the post or page content? One of my favorite theme tricks is to include a script that stripes table rows and turns the table headers into links that trigger a sort function. However, I want to include it only if the post or page content contains a table tag. Listing 7-24 shows how it works.

Listing 7-24. Adding sortable.js if the content contains a table function add_sortable($posts) {

if (stripos($post->post_content, '<table') === false) { $found = true; break;

wp_enqueue_script('sortable', get_bloginfo('stylesheet_directory').'/js/sortable.js'); }

return $posts;

add_filter('the_posts', 'add_sortable');

Here, I've used the filter the_posts(), which lets me pass the array of posts to my function. Then I can loop through the posts, checking to see if the opening table tag is present. If it is, I queue up the table script.

WordPress developer Joost de Valk recently published an updated version of Stuart Langridge's classic table sort script. It turns <th> tags into links. Clicking a heading sorts the table rows, alphabetically or numerically, according to the contents of that column. The updated version of the script also adds alternate row background colors. You can download it at yoast.com/articles/sortable-table/.

0 0

Post a comment