Refer plugin directory path in custom JavaScript file [WordPress]

Updated on September 4, 2023

When developing a WordPress plugin, it’s a good practice to refer relative file names while referring assets (Image, css etc.,) or perform tasks such as Ajax request in JavaScript files. Relative file paths in JavaScript typically refer to files located within the plugin’s directory. In my case I need to refer to the plugin directory in my custom JavaScript file.

How to Refer plugin directory path in custom JavaScript file during WordPress plugin development

To achieve this, we need to follow two-steps.

Step1: Get the Plugin Directory URL in PHP.

In your PHP code (usually in your main plugin file or functions.php), use the ‘plugins_url()’ or ‘plugin_directory_url’ function to retrieve the URL of your plugin’s directory (depending on your requirement) and pass it as a JavaScript variable using ‘wp_localize_script()’. Below is an example:

// Enqueue your JavaScript file and pass the plugins directory URL
wp_enqueue_script( 'custom', plugins_url('/js/custom.js', __FILE__), array(), '1.0.0' );

// Pass the plugin directory URL to the JavaScript file
$args = array( 'pluginsURL' => plugins_url('',  __FILE__),);
wp_localize_script('custom', 'phpFile', $args);
plugins_url vs plugin_dir_url

plugin_dir_url() function internally uses plugins_url() to get the link to plugin directory.

plugin_dir_url() This will return url of the plugin directory with a trailing slash at the end. So this can be easily used to link to the plugin directory.

For ex: http://www.example.com/wp-content/plugins/foo/

plugins_url If no arguments are passed this will deliver the same result as the above function; but with or without a trailing slash at the end. This can be configured to link to files within plugin directory; a useful shortcut.

For ex: plugins_url( ‘img/bar.jpg’ , __FILE__ ) will return a url like http://www.example.com/wp-content/plugins/foo/img/bar.jpg

Ref: https://wordpress.stackexchange.com/a/61698

Step 2: Access the Plugin Directory URL in JavaScript.

Open the JavaScript file js/custom.js, use the code phpFile.pluginsURL variable to access the plugin directory URL and construct my own URL with filename upload.php.

var upurl = phpFile.pluginsURL + "/upload.php";
console.log(upurl);
jQuery.ajax({
                type: 'POST',
                url: upurl,
                data: new FormData(this),
                success: function(data) {
                      // post processing of data
                }
});

This way, we can reference the plugin directory URL in our custom JavaScript file and use it to construct URLs for other assets or perform other tasks such as Ajax request within our WordPress plugin.

Was this article helpful?

Related Articles

Leave a Comment