Using WordPress ‘plugins_url()’ PHP function

The plugins_url() WordPress PHP function retrieves a URL within the plugins or mu-plugins directory. It defaults to the plugins directory URL if no arguments are supplied.

Usage

plugins_url( $path, $plugin )

Custom example:

echo '<img src="' . esc_url( plugins_url( 'images/icon.png', __FILE__ ) ) . '" >';

Output: <img src="http://www.example.com/wp-content/plugins/my-plugin/images/icon.png">

Parameters

  • $path (string, optional): Extra path appended to the end of the URL, including the relative directory if $plugin is supplied. Default: ''
  • $plugin (string, optional): A full path to a file inside a plugin or mu-plugin. The URL will be relative to its directory. Typically this is done by passing __FILE__ as the argument. Default: ''

More information

See WordPress Developer Resources: plugins_url()

Examples

Basic usage

Retrieve the URL for the plugins directory:

$plugins_url = plugins_url();

The $plugins_url variable will equal the absolute URL to the plugins or mu-plugins directory, e.g. http://www.example.com/wp-content/plugins.

Get the URL of an image file in a plugin

Retrieve the URL for an image in the plugin's images directory:

echo '<img src="' . esc_url( plugins_url( 'images/icon.png', __FILE__ ) ) . '" >';

Output: <img src="http://www.example.com/wp-content/plugins/my-plugin/images/icon.png">

Use with a nested file

When using the function in a file that is nested inside a subdirectory of your plugin directory, use PHP's dirname() function:

echo '<img src="' . esc_url( plugins_url( 'images/icon.png', dirname(__FILE__) ) ) . '" >';

Output: <img src="http://www.example.com/wp-content/plugins/images/icon.png">

Get the URL of a JavaScript file in a plugin

Retrieve the URL for a JavaScript file in the plugin's js directory:

$script_url = plugins_url( 'js/script.js', __FILE__ );
wp_enqueue_script( 'my-plugin-script', $script_url );

The script will be enqueued with the correct URL: http://www.example.com/wp-content/plugins/my-plugin/js/script.js

Get the URL of a CSS file in a plugin

Retrieve the URL for a CSS file in the plugin's css directory:

$style_url = plugins_url( 'css/style.css', __FILE__ );
wp_enqueue_style( 'my-plugin-style', $style_url );

The style will be enqueued with the correct URL: http://www.example.com/wp-content/plugins/my-plugin/css/style.css