Layers Plugin Guide: Including Scripts, Styles & Helper Files

Extension Development

Last Updated: for: 1.5.4 Time to Read: 2 minutes

Files may be included within your plugin class contructor, or straight-away in your main plugin file. In either case, you use the PHP  require_once() method. From within a class, you must use your path constant.

From Main File

Use the internal path to your subfolder and file without the leading slash

The following example shows how you might include a helper file from inside __construct(){}   which adds custom meta fields to a post type. We use our dir path constant and then set the subfolder without a leading slash.

Inside the Class

In Variables

When setting variables, we append  our constant to  the internal file path with no leading slash.

If your extension will include custom widgets, you can use our custom register_widgets()   function and hook it onto widgets_init()   as shown in the plugin class tutorial to set the location of the files to be loaded. This uses require_once()   just like including other helper libraries. We use our dir path constant and then set the subfolder without a leading slash.

Files can be included a few other ways explained here:

How to Include and Require Files on Tuts+

Enqueueing provides a safe way to introduce scripts and stylesheets on page load, and ensures code is only executed when required.

Here we make use of WordPress core functions wp_enqueue_script() and wp_enqueue_style() in our custom
function, which we hooked into admin_enqueue_scripts() while setting up our class. WordPress provides two hooks to choose from, admin_enqueue_scripts or wp_enqueue_scripts, depending on if your files should be loaded in the admin or in the front-end. Regardless of the hook you use, the function structure is the same:

Note that we are using constants here for the slug, uri and version, to make things more efficient.

 Admin-only Styles & Scripts

When enqueueing admin scripts or styles, it is best to setup a condition that ensures they only load on the page they are used on. This helps reduce potential script conflicts with other plugins.

In this example, the javascript file for our custom meta will load in the head section of the post editor screen only (edit.php).

Note that this can only be used for admin pages.

Next up, how to add custom post types and templates →