Is the trailing slash '/' only difference between these two? If so, I can use trailingslashit(__DIR__)?
Is the trailing slash '/' only difference between these two? If so, I can use trailingslashit(__DIR__)?
plugin_dir_url(__FILE__) This function provides you the url of the file directory.
plugin_dir_url(__DIR__) This function provides you the url plugins folder.
__FILE__ this magic constant will give you the path of file where the file is exist.
__DIR__ this magic constant will give you the path of directory where the file is exist.
trailingslashit(__DIR__) this function will return the path of directory and add shash after the path of directory.
plugin_dir_path(__FILE__). will give you same result as trailingslashit(__DIR__). and my suggestion to use plugin directory path because it is a wordpress way.
/home/www/your_site/wp-content/plugins/your-plugin/includes/
This can be used for loading PHP files.
more info : https://developer.wordpress.org/reference/functions/plugin_dir_path/
http://example.com/wp-content/plugins
more info : https://codex.wordpress.org/Function_Reference/plugins_url
http://example.com/wp-content/plugins/
The latter two are useful to load images, stylesheets, JS.
more info : https://codex.wordpress.org/Function_Reference/plugin_dir_url
Lets untrail what is happening:
The wordpress function is as simple as this:
function plugin_dir_path( $file ) {
return trailingslashit( dirname( $file ) );
}
So,
include plugin_dir_path(__FILE__) . 'xx.php';
Is equal to
include trailingslashit( dirname( __FILE__ ) ) . 'xx.php';
In PHP 5.3, __DIR__ was introduced as a replacement for dirname( __FILE__ ).
If you don't need to support PHP < 5.3 (you don't), it can be reduced to:
include trailingslashit( __DIR__ ) . 'xx.php';
(also see this : Is there any difference between __DIR__ and dirname(__FILE__) in PHP?)
As __DIR__ doesn't return something with a trailing slash, there is no need to do the trailingslashit thing. So we can reduce further to:
include __DIR__ . '/xx.php';
So, to conclude, the following lines all does the exact same thing (on PHP >= 5.3):
include plugin_dir_path(__FILE__) . 'xx.php';
include trailingslashit( dirname( __FILE__ ) ) . 'xx.php';
include trailingslashit( __DIR__ ) . 'xx.php';
include __DIR__ . '/xx.php';
Which is best? I prefer the last one. You don't have to type as much, it is less noisy, and you don't have to worry about what magic is inside that plugin_dir_path function. And this is how you usually include files in PHP. Some priests may say you should do it the Wordpress way. Be a rebel!