Văn Cao Trần Văn Cao Trần - 6 months ago 50
PHP Question

How to include wordpress plugins files

I have two folders and two files in my wordpress lugin are:


How to include one file1.php into the file2.php?

I used this code in file2.php

include_once( plugin_dir_path( __FILE__ ) . '/folder1/file1.php');

but it returned an error.


The function plugin_dir_path(), can not be use like this with your file and folder configuration.

It returns an error because the file is not found.


Will get the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in (file2.php in your case).

In your case, in file2.php, it will return : /path/wp-content/plugins/your-plugin/folder2/folder1/file1.php

The workaround:

In the main plugin file, you can add a define constant

defined('MYPLUGIN_DIR') or define('MYPLUGIN_DIR', plugin_dir_path( __FILE__ ));

Now MYPLUGIN_DIR is available in any file. In file2.php:

include_once( MYPLUGIN_DIR . 'folder1/file1.php');

Will return : /path/wp-content/plugins/your-plugin/folder1/file1.php

Hope it helps !