Reputation: 1060
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.
Upvotes: 2
Views: 12094
Reputation: 9
I know this is an old question, but I had the same issue and I made my own solution. If anyone still needs the answer, here it is.
If you're sure the class will be in a plugin or theme, you can use the WP_CONTENT_URL and WP_CONTENT_DIR constants, along with __DIR__, to find the URL of the current working directory. Just replace WP_CONTENT_DIR with WP_CONTENT_URL in __DIR__ and you're all set.
function getCurrentDirUrl(){
return str_replace(WP_CONTENT_DIR,WP_CONTENT_URL,__DIR__);
}
Upvotes: 0
Reputation: 1807
Since you're working in WordPress, the WordPress-specific way of doing this is to use get_stylesheet_directory_uri()
. It will return the URL for the current theme (or child theme). See https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/ for full details.
Upvotes: 1
Reputation: 1951
__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);
Upvotes: 6
Reputation: 11
Try this solution from this url:
PHP: How to get URL of relative file
But instead of using preg_replace
try using str_replace
.
Upvotes: 0