1

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.

Darren Cooney
  • 1,012
  • 16
  • 25
  • An example of what you want to get? What have you tried? You would probably want to check [get_site_url()](https://developer.wordpress.org/reference/functions/get_site_url/)... something like `$file_relative_path = "..."; $url = get_site_url(null, $file_relative_path, 'https');`? – Alejandro Iván May 05 '17 at 00:23
  • This can be used in a theme or plugin, so get_site_url doesn't work. The class directory should be able to be dropped anywhere, so I can't rely on WordPress core functions. – Darren Cooney May 05 '17 at 00:26

3 Answers3

5

__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);
Ryan Tuosto
  • 1,941
  • 15
  • 23
1

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.

Martin_W
  • 1,582
  • 1
  • 19
  • 24
0

Try this solution from this url:

PHP: How to get URL of relative file

But instead of using preg_replace try using str_replace.

Community
  • 1
  • 1
K.Martinez
  • 11
  • 5