In this code snippet we are going to look into how you get a full path of a plugin file. When you are developing a plugin you can store multiple file types in it such as CSS or JS files where you need to access the full URL for the file, or you could have another PHP file which you want to include by calling the full directory path. As the plugin directory is inside the wp-content folder the path to the directory could be quite large.
http://example.com/wp-content/plugin-name/plugin/frontend/css/css-file.css
The above is what you would have to use to include a stylesheet into your application from a plugin. If you were calling this from a file inside the frontend folder you would use the following code.
function plugin_styles() {
wp_enqueue_style( 'css-styles', 'http://example.com/wp-content/plugin-name/plugin/frontend/css/css-file.css' );
}
add_action( 'wp_enqueue_scripts', 'plugin_styles' );
The problem we have when building a WordPress plugin you have to assume that this plugin can be used on any site on any WordPress install. Because it can be used on any site you can not include your domain inside the a wp_enqueue_style function. As a WordPress site can change the location of the wp-content directory with a wp-config constant you can not assume that wp-content is located off the root of the domain. To include this correctly from a file inside the frontend folder you should be using a WordPress function of plugin_dir_url(), that will return the full URL of the current directory.
function plugin_styles() {
wp_enqueue_style( 'css-styles', plugin_dir_url( __FILE__ ) . 'css/css-file.css' );
}
add_action( 'wp_enqueue_scripts', 'plugin_styles' );
But what if you don't want the URL for the folder but want the full file path so that you can include a new PHP file instead of doing the following.
include_once '/home/user/var/www/vhost/website/wp-content/plugin-name/plugin/frontend/new-file.php';
You can use a WordPress function of plugin_dir_path() to get the full path of the folder.
include_once plugin_dir_path( __FILE__ ) . 'new-file.php';
You could also use this function to include all the files within a directory by using the PHP function glob.
foreach(glob( plugin_dir_path( __FILE__ ) . '*.php') as $file)
{
include_once $file;
}