Helper Function For Registering JavaScript and Stylesheets with WordPress

If you wish to register WordPress JavaScript and/or stylesheet dependencies, the API provides functions that make this easy – it’s straightforward both for JavaScript and for stylesheets.

Whenever you’re doing any kind of work in which you find yourself making frequent calls to these functions, it may help to include a helper function to make it a bit easier.

Here’s an example function that I’ve used in a few of my projects:

/**
 * Helper function for registering and loading scripts and styles.
 *
 * @name	The identifier to register with the WordPress API
 * @file_path	The path to the actual file
 * @is_script	Optional argument for if the incoming file_path is a JavaScript source file.
 */
private function _load_file($name, $file_path, $is_script = false) {

	$url = $url = plugins_url( $file_path, __FILE__ );
	$file = plugin_dir_path( __FILE__ ) . $file_path;

	if( file_exists( $file ) ) {

		if( $is_script ) {

			wp_register_script( $name, $url, array( 'jquery' ) );
			wp_enqueue_script( $name );

		} else {

			wp_register_style( $name, $url );
			wp_enqueue_style( $name );

		} // end if

	} // end if

} // end _load_file

An example use case is as follows:

$this->_load_file( 'my-plugin-admin', '/my-plugin/css/my-plugin-admin.css' );

Although it’s not much, this can save a bit of time if you’re frequently working to register a number of different script and style dependencies.

Leave a Reply

Name and email address are required. Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>