-1

So I'm currently working on a plugin using the boilerplate plugin structure. The problem comes up when I try to include a folder full of files that are needed for my project. I go to the admin class and I include everything from this folder using this code:

foreach(glob('folder/*.php' ) as $file) {
    include_once $file;
}

This produces an error when I create an instance of one of the classes I'm including. If I do not create instances, there is no error.

Though, if I use this code on the top of the file everything works as expected.

include_once('folder/class1.php');
include_once('folder/class2.php');
include_once('folder/class3.php');
include_once('folder/class4.php');
include_once('folder/class5.php');
  • So which error does it produce? :) How is it specific to WP rather than general PHP mechanics? – Rarst Jul 5 '17 at 9:32
  • In PHP i tested it and it works fine with foreach(glob('folder/*.php' ) as $file) { include_once $file; } but Wordpress was not working some times, strange behavior. – MashRoofa Jul 5 '17 at 12:29
  • So using the plugin_dir_path( FILE ) fixed the problem – MashRoofa Jul 5 '17 at 12:31
0

By the WP coding guide, please, use WP Plugin API. In your case place the following code into start of the main .php file of the plugin.

// Working directory definition.
define( 'MY_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );

// Attaching executable
require_once MY_PLUGIN_DIR . 'folder/class-my-class.php';
  • 1
    Thank you so much, after using the constant it worked fine! define( 'MY_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); foreach(glob(MY_PLUGIN_DIR . 'file/*.php' ) as $file) { include_once $file; } – MashRoofa Jun 29 '17 at 12:55
  • Cool. Else I recommend you use require_once directive. If some error will occur while loading a file , you won't know about this, because include_once simply generates a PHP Notice while require_once throws an Error. – Paul Burilichev Jun 29 '17 at 22:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.