Enqueue

A plugin or theme wouldn’t do much if it wasn’t for enqueuing javascript or css stylesheets. Enqueue comes in handy for this purpose.

How to install

Make sure you have read the extension installation guide first.

To install this extension, place the following inside the “require” block of the composer.json file.

Now run composer install  in your terminal. Thats it!

Usage - Scripts

We will be using a main plugin class to see the various examples, as the code gets much cleaner and consistent. Note that the same will go for a theme (functions.php) file.

The basics for scripts

For basic demonstration, lets enqueue jQuery (which comes shipped with WordPress) on the front-end:

To enqueue at the back-end, use admin_enqueue_scripts on line 44.

Custom js script

Okay, jQuery was a very simple example. Lets enqueue a custom js script which depends on jQuery.

Localizing js variables

What if we needed to push variables so that we could consume them in our scripts? Well, its simple!

Line 36 will create a js object for use in your script.

External scripts

If you need to enqueue an external script (outside of your plugin directory), use raw_script.

Multiple dependencies or localized vars

If your script depends on multiple scripts and/or parameters, just add them as you would for a single dependancy script or parameter.

You can also pass multiples as an array instead of multiple calls.

Usage - Stylesheets

The basics for styles

For basic demonstration, lets enqueue Color Picker (which comes shipped with WordPress) on the front-end:

To enqueue at the back-end, use admin_enqueue_scripts on line 44.

Custom css stylesheet

Okay, that was simple enough. Lets enqueue a custom css stylesheet which depends on Color Picker.

External stylesheets

Lets enqueue an external css stylesheet (outside your plugin directory) by using raw_style

Multiple dependencies

If your stylesheet depends on multiple stylesheets, repeat the statements.

You can also pass multiples as an array instead of multiple calls.

Khan

A die hard programmer!