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);
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.