Is the trailing slash '/' only difference between these two? If so, I can use trailingslashit(__DIR__)
?
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
Usage. echo get_template_directory(); Returns an absolute server path (eg: /home/user/public_html/wp-content/themes/my_theme), not a URI. In the case a child theme is being used, the absolute path to the parent theme directory will be returned.
you can use content_url() it's located with http://www.example.com/wp-content wp-content folder. you can use WP_CONTENT_DIR it'll located to wp-content folder.
Using the plugin_dir_path() function will return the path of the file's directory from where it is called.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With