Using WordPress ‘plugin_dir_url()’ PHP function

The plugin_dir_url() WordPress PHP function retrieves the URL directory path (with a trailing slash) for the plugin FILE passed in.

Usage

plugin_dir_url( $file )

Example:

Input:

echo plugin_dir_url( __FILE__ ) . 'assets/image.png';

Output:

http://example.com/wp-content/plugins/my-plugin/assets/image.png

Parameters

  • $file (string) – The filename of the plugin (FILE).

More information

See WordPress Developer Resources: plugin_dir_url()

Examples

Enqueue CSS File

This example shows how to enqueue a CSS file for your plugin.

function myplugin_enqueue_styles() {
    wp_register_style('myplugin-styles', plugin_dir_url(__FILE__) . 'assets/myplugin-styles.css');
    wp_enqueue_style('myplugin-styles');
}
add_action('wp_enqueue_scripts', 'myplugin_enqueue_styles');

Enqueue JavaScript File

This example demonstrates enqueuing a JavaScript file for your plugin.

function myplugin_enqueue_scripts() {
    wp_enqueue_script('myplugin-script', plugin_dir_url(__FILE__) . 'js/myplugin-script.js', array('jquery'), '', true);
}
add_action('wp_enqueue_scripts', 'myplugin_enqueue_scripts');

Load Image in Plugin Folder

This example shows how to load an image from the plugin’s assets folder.

$image_url = plugin_dir_url(__FILE__) . 'assets/image.jpg';
echo '<img src="' . $image_url . '" alt="Sample Image">';

Enqueue CSS and JavaScript Files for Admin Area

This example demonstrates how to enqueue CSS and JavaScript files specifically for the admin area.

function myplugin_admin_enqueue_scripts() {
    wp_enqueue_script('myplugin-admin-script', plugin_dir_url(__FILE__) . 'js/myplugin-admin.js', array('jquery'), '', true);
    wp_enqueue_style('myplugin-admin-styles', plugin_dir_url(__FILE__) . 'css/myplugin-admin.css');
}
add_action('admin_enqueue_scripts', 'myplugin_admin_enqueue_scripts');

This example shows how to create a settings link for your plugin in the plugins list page.

function myplugin_settings_link($links) {
    $settings_link = '<a href="options-general.php?page=myplugin-settings">' . __('Settings', 'textdomain') . '</a>';
    array_unshift($links, $settings_link);
    return $links;
}
$plugin = plugin_basename(__FILE__);
add_filter("plugin_action_links_$plugin", 'myplugin_settings_link');