WP Enqueue script for WordPress themes gives better control on how, which and when you want to load your javascript or css files like html pages. This is less known but very powerful Function of WordPress – both for Plugins and Themes. You can control the source – that simply means, you can directly inject these static files from different CDN.
WP Enqueue script for WordPress Themes : Official Function Reference
You will get all the official reference of WP Enqueue script on WordPress Codex along with Examples :
1 | http://codex.wordpress.org/Function_Reference/wp_enqueue_script |
As WP Enqueue script is a basic WordPress function, a good theme, theme framework’s child theme will nicely handle the feature. All you need to do is to add the snippet in the functions.php file of the active theme or theme framework’s child theme :
---
1 2 3 4 5 6 | function theme_name_scripts() { wp_enqueue_style( 'style-name', get_stylesheet_uri() ); wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'theme_name_scripts' ); |
Do not add PHP opening or closing tags – often they are shown in examples.
Practical Usage of WP Enqueue script for WordPress Themes
Nothing is useful if has no practical value, thats true for WP Enqueue script function. WP Tut Plus has a great topic :
1 | http://wp.tutsplus.com/tutorials/the-ins-and-outs-of-the-enqueue-script-for-wordpress-themes-and-plugins/ |
We can :
- De-register all the default script loading and load via WP Enqueue script function
- In the same principle, we can serve a minified, combined CSS or Javascript without any plugin
- We can add Icon CSS files, which are typical for newer themes
- We can add logics for conditional loading only like if ( is_front_page() )
- Helpful during development of a Theme – we can compare the revisions
Tagged With Practical example of enqueue script in wordpress , wordpress wp_enqueue_script template