I have a file that can either be included in a plugin, or in a theme. What’s the best way to get the URL of the file’s folder (from within the file)?
Edit:
I’m now using this for now
home_url( '/' . str_replace( ABSPATH, "", dirname( __FILE__ ) ) );
Let me know if there’s any problem with this / there’s a better way.
See Determining Plugin and Content Directories.
⦠returns the full URI to the file in your plugin. For themes you use:
Using ABSPATH and
home_url()
might not work if the wp installation is in a different directory to the url it is displayed at. You should test that out.My thought is using the content directory as a place to do the replacement might be more robust as you can pass the resulting path into
content_url()
which accounts for where the WP installation is:This could be simplified for unix only but the above supports windows too.
Why won’t you write both case and check which one is actually pointing to a real file:
That’s the best option I would see.
I suggest you use a filter.
In your file, somewhere at the very beginning, include something along the lines of:
Then, in the code that needs to reference the file, apply the filter to an empty string:
TL;DR
Given the file path…
Results to…
Problem
Building a plug-and-play library for wordpress that can either be “included” inside a theme or plugin can be difficult. WordPress has no pre-defined function for getting the URL of that file.
Solution
Treat plugins and themes separately.
Step 1. Check whether included inside theme or plugin
Step 2a. If inside a theme
Step 2b. If inside a plugin
should do the trick.