Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Relative File Paths in PHP


PHP, WordPress
David Egan

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
// function is called in a subdirectory nested two deep from the project root
plugin_dir_path( dirname ( dirname( __FILE__ ) ) ) . 'includes/class-staff-area-access.php' ;

// This achieves the same result, using the __DIR__ magic constant:
echo plugin_dir_path( dirname( __DIR__ ) ) . 'includes/class-staff-area-access.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:

// PHP 7:
echo dirname( __DIR__ , 2 ) . '/includes/class-staff-area-access.php' ;

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