WP-Mix

A fresh mix of code snippets and tutorials

Include files from parent directory, subdirectory

This post concludes our trilogy of posts on getting file and directory path information with PHP and WordPress. In this final path-related post, you’ll get numerous ways to get and include files from parent directories, subdirectories, adjacent directories, and even the same directory, just to round things out.

Get parent directory from within sub-directory

For WordPress plugins, here is how to get and/or include a file that is located in the parent directory:

// get file path
echo dirname(plugin_dir_path(__FILE__)) . '/example.php';

// include file
require_once(dirname(plugin_dir_path(__FILE__)) . '/example.php');

Note that you can customize this code snippet by editing example.php with the file that you would like to get or include.

Get subdirectory from within parent directory

For WordPress plugins, here is how to get and/or include a file that is located in a subdirectory:

// get file path
echo plugin_dir_path(__FILE__) . 'inc/example.php';

// include file
require_once(plugin_dir_path(__FILE__) . 'inc/example.php');

Note that you can customize this code snippet by editing inc/example.php with the path and file that you would like to get or include.

Get subdirectory from within same subdirectory

For WordPress plugins, here is how to get and/or include a file that is in the same subdirectory:

// get file path
echo plugin_dir_path(__FILE__) . 'example.php';

// include file
require_once(plugin_dir_path(__FILE__) . 'example.php');

And here is how to do it without using WordPress:

// get file path
dirname(dirname(__FILE__)) . '/inc/example.php';

// include file
require_once(dirname(dirname(__FILE__)) . '/inc/example.php');

Note that you can customize this code snippet by editing /inc/example.php with the path and file that you would like to get or include.

Get any same-level directory

For WordPress plugins, here is how to get and/or include a file that is located in any same-level subdirectory:

// get file path
echo dirname(plugin_dir_path(__FILE__)) . '/inc/example.php';

// include file
require_once(dirname(plugin_dir_path(__FILE__)) . '/inc/example.php');

To get a different-level directory, check out the levels parameter of the PHP’s dirname function. Note that you can customize this code snippet by editing /inc/example.php with the path and file that you would like to get or include.

Get file from same directory

With or without WordPress, we can get and/or include a file that is located in the same directory:

// get file
dirname(__FILE__) . '/example.php';

// include file
require_once(dirname(__FILE__) . '/example.php');

Note that you can customize this code snippet by changing example.php to the name of the file that you would like to get or include.

WP-Mix File-Path Trilogy

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress