I have a PHP Class written for use in WordPress themes or plugins that loads some JS and CSS using enqueue_script
and enqueue_style
when the Class is initialized.
I need to dynamically get the URL (not the absolute path) to the directory the Class is being loaded so I can pass this URL to enqueue_script
and enqueue_style
for asset loading.
Directory Structure wp-content ├── themes │ ├── theme_name │ │ ├── my_class │ │ │ ├── my_class.php │ │ │ ├── js (need URL) │ │ │ │ ├── file.js* │ │ │ ├── css │ │ │ │ ├── file.css*
Is there a PHP function that works like [dirname][1]
but returns a file URL not a path?
EDIT
The my_class
directory should be able to be dropped anywhere, in a theme or plugin, so I can't rely on WordPress core functions to get the URL to the class dir.
Try this solution from this url:
PHP: How to get URL of relative file
But instead of using preg_replace
try using str_replace
.
__DIR__
will give you the file path to the folder of the current script and then you can simply remove your document root (the path to the folder your files are hosted out of) and then you are left with the url path:
$file_path = __DIR__;
$url_path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $file_path);