Loading Assets

This article is part of the WordPress guide. Read the introduction.

Table of Contents

What if you wanted to load a CSS file to style your output? Or a JS file to spice it up on the frontend? Well, it turns out it’s not much different than it was with themes.

We’re still loading assets using the enqueue system. The only real difference is how we get the URL and path to the file. Let’s add a style.css file to our plugin directory and load it on the frontend. Here’s the additional code we need to add to our main file:

PHP
function pgn_enqueue_styles() {
    wp_enqueue_style(
        'pgn-style',
        plugins_url( 'style.css', __FILE__ ),
        [],
        filemtime( plugin_dir_path( __FILE__ ) . 'style.css' ) // auto-versioning trick
    );
}
add_action( 'wp_enqueue_scripts', 'pgn_enqueue_styles' );

Remember the functions for getting the file’s URL or path in themes? Like get_theme_file_uri(), get_template_directory(), etc. There are 4 of those for plugins:

  • plugins_url( $path, $plugin ) – retrieves a URL within the plugins directory.
    • $path – path appended to the end of the URL.
    • $plugin – a full path to a file inside the plugin directory. The URL will be relative to its directory. If not supplied, the URL will use the plugins directory (usually /wp-content/plugins/).
    • The most common and robust way to use plugins_url() is by providing two arguments: the relative path to the asset, and the magic constant __FILE__. plugins_url(‘style.css’,__FILE__) tells WordPress: “Return the URL for style.css located in the same directory as the current PHP file.”.
  • plugin_dir_url( $file ) – wrapper over plugins_url( ”, $file ). Returns the URL directory path for the file passed (with trailing slash). E.g., https://example.com/wp-content/plugins/post-reading-time/.
  • plugin_dir_path( $file ) – same as plugin_dir_url() but returns the filesystem path rather than a URL. It’s a wrapper for trailingslashit( dirname( $file ) ).

plugin_basename( $file ) – returns the relative path to the plugin file in the plugins directory. E.g., ‘post-reading-time/includes/passed-file.php’.

Table of Contents