4

plugins_url() function accepts plugin slug or file path to build URL for.

I have following directory structure:

/wp-content/mu-plugins/someplugin/css/file.css
/wp-content/mu-plugins/someplugin/includes/file.php

I need to build URL to file.css in file.php. I can't pass __FILE__ because that will be one level too deep.

plugins_url('css/file.css', __FILE__ )

I can pass __DIR__ to get correct level and it seems to work, but it's not documented as allowed and I am not sure there isn't something to bite me later with this.

plugins_url('css/file.css', __DIR__ )

So, is this adequate? Any better way to build URL for these conditions?

  • I would save the main plugin file in a global variable and use that everywhere, certainly in included files. So $wpse15731_file would end with mu-plugins/someplugin/someplugin.php, and it doesn't matter that my code is in includes/file.php or somewhere else. – Jan Fabry Apr 27 '11 at 11:23
  • @Jan Fabry main stuff not up to me, I just merge new chunk into larger project – Rarst Apr 27 '11 at 11:32
4

__DIR__ is rather new and not always supported. Use dirname( __FILE__ ).

plugins_url() is using …

$folder = dirname(plugin_basename($plugin));

… so yes, it is safe.

Just use plugins_url( 'subfolder/file.css', dirname( __FILE__ ) )

  • Probably, but the main question - is it safe to pass directory path instead of file path at all to this one? – Rarst Apr 27 '11 at 10:30
  • Oops, I completed my answer. – fuxia Apr 27 '11 at 10:36
  • @toscho that just moves question level deeper - plugin_basename() is supposed to take file path as well. – Rarst Apr 27 '11 at 10:46
  • @Rarst A directory is just a special file. Looking at the code for plugin_basename() I don’t see anything that may break if you pass a directory. – fuxia Apr 27 '11 at 10:51
  • 2
    As long as the second parameter you pass to plugins_url ends with yourplugin-dir/somethingelse[/], dirname() can chop off the /somethingelse part, and plugins_url gets yourplugin-dir as it needs. So it does not matter whether somethingelse is a file or a dir, it doesn't need to exist. – Jan Fabry Apr 27 '11 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.