I found myself in the same situation, I\'m developing a library that I don\'t know where will it be included by other users, so I cannot provide an absolute path.
What can we use to achieve it?
With this, we can remove the ABSPATH
from __DIR__
, obtaining a relative path to the current file\'s directory from the WordPress root, so that it works when it gets appended to the site url.
Code example
Let\'s suppose that we have the following files structure:
-> /inc
-> current-file.php
-> /assets
-> your-file.js
-> your-file.css
The following code would work:
// Get the path from the WordPress root to the current file\'s directory
$current_path = str_replace( ABSPATH, \'/\', __DIR__ );
// Relative path from the current file\'s directory to your asset.
$relative_path = \'/assets/your-file.js\'
// Enqueueing a script
wp_enqueue_script( \'your-handle\', $current_path . $relative_path );
// Enqueueing a stylesheet
wp_enqueue_style( \'your-handle\', $current_path . $relative_path );
Or we can write it shorter if we don\'t worry about readability (I don\'t in this case):
// Scripts
wp_enqueue_script( \'your-handle\', str_replace( ABSPATH, \'/\', __DIR__ ) . \'/assets/your-file.js\' );
// Stylesheets
wp_enqueue_style( \'your-handle\', str_replace( ABSPATH, \'/\', __DIR__ ) . \'/assets/your-file.css\' );
Notice that in the case that our asset was located in a directory above the file where we are enqueueing it, the relative path should be something like \'/../assets/your-file.js\'
.
Here is another example:
-> /inc
-> current-file.php
-> /assets
-> your-file.js
-> your-file.css
And then
// Scripts
wp_enqueue_script( \'your-handle\', str_replace( ABSPATH, \'/\', __DIR__ ) . \'/../assets/your-file.js\' );
// Stylesheets
wp_enqueue_style( \'your-handle\', str_replace( ABSPATH, \'/\', __DIR__ ) . \'/../assets/your-file.css\' );
I hope this helps if anyone else wonders how to enqueue a script without knowing the final path of the file beforehand.