Relative File Paths in PHP
PHP, WordPress
Relative file paths are used when including or requiring files.
In the context of a WordPress plugin or theme, you may be referencing a file that is in a ‘parallel’ directory.
In the example below, the plugin root directory is referenced by multiple use of the PHP dirname()
function.
dirname()
returns a parent directory’s path.
- Target file:
/includes/class-staff-area-access.php
- Originating file:
/admin/partials/access-check.php
Notes on the PHP Magic constants:
__FILE__
- the full path and filename of the file (with symlinks resolved)__DIR__
- the directory of the file
dirname() in PHP 7
In PHP 7, dirname()
will accept an optional levels parameter. This means the above code could be replaced with:
WordPress Function: plugin_dir_path()
The WordPress function plugin_dir_path()
gets the filesystem directory path for the file passed in. It includes a trailing slash.
The function is a wrapper for trailingslashit( dirname( $file ) )
Resources
comments powered by Disqus