
Sometimes you want to load one script in only specified posts, not for all posts. For example: you want load Thinkbox script only when post has images, load SyntaxHighlighter only when post has codes. It wouldn't be optimized if you always load these scripts in every posts. We just want WordPress to load them when we need based on post content.
To load script only when it's needed, we have to check the post content for the sign of present of the script. In case of Thickbox, the sign is a string class="thickbox"
in the post content. In case of SyntaxHighlighter, it's the tag pre
. In most cases, script comes with style, so we have to concern about the style, too.
For better understanding the idea, we'll see the code for conditional loading Thickbox (paste into the functions.php
file):
add_action('wp_print_styles','my_conditional_script'); function my_conditional_script() { global $post; if (is_single() && strpos($post->post_content, 'class="thickbox"') !== false) { wp_enqueue_script('thickbox'); wp_enqueue_style('thickbox'); } }
The code will check if current page is a post with is_single()
and check the existence of string class="thickbox"
in the post content. If conditions match, then it will add the thickbox script and style. We use the action wp_print_styles
to make sure both script and style are added in the header.
If we want to check for the SyntaxHighlighter, we can expand the code as the following:
add_action('wp_print_styles','my_conditional_script'); function my_conditional_script() { global $post; if (is_single() && strpos($post->post_content, 'class="thickbox"') !== false) { wp_enqueue_script('thickbox'); wp_enqueue_style('thickbox'); } if (is_single() && strpost($post->post_content, '<pre') !== false) { $style = get_stylesheet_directory_uri() . '/syntaxhighlighter/style.css'; wp_register_style('sh-style', $style); wp_enqueue_style('sh-style'); $script = get_stylesheet_directory_uri() . '/syntaxhighlighter/script.js'; wp_register_style('sh-script', $script); wp_enqueue_style('sh-script'); } }
In this code, we assume that the SyntaxHighlighter script is put in the subfolder /syntaxhighlighter/
of theme folder. It has 2 files: style.css
for style and script.js
for script. The code will register these files, and print it in the header. If you're using a SyntaxHighlighter script with many files (css and js), you can repeat the code to register and add them all.
By using the conditions of loading script, we can make our users download the script only when it's needed. The straight advantage you can see is: the page size and the page loading time when decrease when users request posts that no need to load the script. How many posts that don't need the script like Thickbox and SyntaxHighlighter? In case of my blog it's about 80%. It means 80% of my posts will be optimized, isn't it cool?.