Referring to a directory can sometimes be challenging! to fix this issue WordPress has many functions to retrieve correct directory paths for developers. one of the functions is plugin_dir_path which is responsible for retrieving the current plugin directory inside WordPress.
When it comes to including multiple files inside a plugin, the
plugin_dir_path function becomes super helpful.
It’s popular for WordPress developers to use the
plugin_dir_path function for including PHP files into each other.
Get Plugin Directory Path Using plugin_dir_path Function
plugin_dir_path function in WordPress is available if you need a complete path to your plugin’s directory.
plugin_dir_path function syntax
The function syntax is pretty easy:
$file parameter’s value must be a string.
I saw lots of developers using the
dirname(__FILE__) value for
$file in the main file of their plugins.
Keep reading; We’ll try the most common usage of
plugin_dir_path function in an example:
plugin_dir_path function to get the plugin directory path
Using this code inside your custom plugin is useful.
To make it possible for us to use our main plugin directory in a variable everywhere, we can
define It with PHP:
define('MY_CUSTOM_PLUGIN_DIR', plugin_dir_path(dirname( __FILE__ )));
Remember that this code works in the main file of a plugin.
For future usage of defining
MY_CUSTOM_PLUGIN_DIR, I have an example for you:
$cssUrl = MY_CUSTOM_PLUGIN_DIR . '/css/plugin-style.css';
You can use the defined variable everywhere you want inside your plugin.
Also, you can get the path to the WordPress root directory with the
get_home_path function if needed (or
ABSPATH constant). Sometimes it’s a better option to use instead of
If you are not familiar with the process of creating a WordPress plugin, you better read my tutorial:
To keep more into it, you can read the plugin_dir_path function code reference on the WordPress official website for developers.
What do you think about "How to Get Plugin Directory Path in WordPress (+Example)"?