I am curious as there are three function for loading files in plugins:
plugin_dir_path()
and plugins_url()
, along with plugin_dir_url()
So as a plugin developer, which would you use for loading php files? the main example shows: plugin_dir_path()
– but if one were to write an auto loader function, which function would you use?
Return values of the three mentioned functions
1.
plugin_dir_path( __FILE__ )
returns the servers filesystem directory path pointing to the current file, i.e. something along the lines of/home/www/your_site/wp-content/plugins/your-plugin/includes/
This can be used for loading PHP files.
2.
plugins_url()
returns the web address of the current WordPress installation’s plugin folder, i.e. something along the lines ofhttp://example.com/wp-content/plugins
3.
plugin_dir_url()
behaves in a very similar fashion toplugins_url()
. It also returns a web address, but with a trailing slash, i.e. something along the lines ofhttp://example.com/wp-content/plugins/
The latter two are useful to load images, stylesheets, JS and the like.
Use-cases
Use-cases as from the main plugin file:
plugin_dir_path()
is the only one of the three that gives you the local filesystem path, ie:/var/www/site.com/wp-content/plugins/your-plugin/
, and would be used for loading php files.The other two are for retrieving public-facing URLs for loading assets like images, CSS, and JS files, ie:
http://site.com/wp-content/plugins/your-plugin/
.This answer explains the difference between
plugins_url()
andplugin_dir_url()
.