Working With wp_register_script()

WordPress allows you to register your own script files with theme. This allows you to link the script file to WordPress generated page according to the dependencies and at right time. The traditional way of including scripts, i.e. by adding <script> tag in head or footer have some drawbacks. In traditional way, we hardcode the script and load it every time with page, even though it is not needed. But once you register the script with theme, it can be loaded dynamically. This allows you to improve your performance and make your website more faster.

So how to register a script?

Quite simple. Just use following syntax for registering your scripts.

<?php wp_register_script( $handle, $src, $deps, $ver, $in_footer ); ?>

Parameters:

$handle

‘handle’ is nothing but name of your script. You can give any name to your script but make sure that they are unique throughout your theme. No two scripts can have same name.

$scr

‘src’ is the url to your script. You can pass any url as parameter. Example: you can use “//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min.js” for registering Angular JS.

$deps

If your script depends on other scripts then you can specify all those other scripts in an array. This parameter will make sure that all the dependent scripts are loaded before this script.

$ver

‘ver’ specifies version number and it is added in your query string. If you have not specified the version number or specified it as ‘false’ then by default your current version number of WordPress will be added. If you set is as ‘null’ then no version number will be added to your query string. I would like to suggest you to set it as null which will help you to improve performance.

$in_footer

If you specifies this parameter as ‘true’ then script will be loaded in footer. For proper functioning of this parameter you will need wp_footer() hook in your theme at appropriate place. If you do not set this parameter then the script will be loaded in <head> of your theme.

How to use registered script in your theme?

To use your registered script in you have to use wp_enqueue_script(). Simply pass name of your script i.e. handle as parameter and WordPress will take care of rest.

Say we have ‘ankurcus‘ as handle for our registered script the we will use following line to load ‘ankurcus‘ with our theme.

<?php wp_enqueue_script('ankurcus'); ?>

That’s all. Now you have learned to register your custom scripts with WordPress and use them in your theme.

Reference:

You can visit following WordPress codex pages for more information.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.