How to get Plugin Directory Path in WordPress? (+Example)

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.

5 from 5
from 1 user
(Rate this post)

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

The 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:

plugin_dir_path($file)

$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 usage example

Using this code inside your custom plugin is really useful.

To make it possible for us to use our main plugin directory in a variable everywhere, we can define it using PHP:

define('MY_CUSTOM_PLUGIN_DIR', plugin_dir_path(dirname( __FILE__ )));

Keep in mind 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.

If you are not familiar with the process of creating a WordPress plugin, you better read my tutorial:

How to create a Hello World plugin for WordPress in 3 Steps

To deep more into it, you can read 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)"?

Your rating submit was successfull.

Your rating submit was not successfull.

Menu