Văn Cao Trần
Văn Cao Trần

Reputation: 117

How to include wordpress plugins files

I have two wordpress plugin folders and two files like so:

/my-plugin/folder1/file1.php and my-plugin/folder2/file2.php

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.

Upvotes: 1

Views: 1216

Answers (1)

Benoti
Benoti

Reputation: 2210

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.

plugin_dir_path(__FILE__) 

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 !

Upvotes: 1

Related Questions