I'm writing a plugin, and near the top of the main plugin file I have a series of require_once statements as is typical.

After more than ten hours of trying to figure out why WP couldn't find my classes, I finally landed on this -- if I had:

require_once( 'includes/myclassfile.php' );

it failed. But if I explicitly put in the base path like so:

define ( 'MY_DIR', rtrim( plugin_dir_path( __FILE__ ), '/' ) );
require_once( MY_DIR . '/includes/myclassfile.php' );

it worked.

So my question is: why didn't the first form work? My IDE (PhpStorm) understood it, the boilerplate I started from used it, and I have other plugins installed that use that form, and they work. What could have been different about this case?

Edit: This question got marked as duplicate of another that also addressed confusion about the proper use of require, however in that case, the final conclusion was the opposite of what worked for me. I am not asking what to do, but why one version would fail. Isaac's answer suggests a reason, but it is unsatisfying since there are other top-level plugins in my wordpress install that do work with the form that doesn't work for mine --- I would like to know what makes mine different.

(Just to be complete, here is the full plugin file:)

/*
 * Plugin Name: A Strenga Projects
 * Version: 1.0
 * Description: Projects for Strenga
 * Author: DD
 */
if ( ! defined( 'ABSPATH' ) ) exit;

define ( 'STRENGA_PROJECTS_DIR', rtrim( plugin_dir_path( __FILE__ ), '/' ) );    
require_once( STRENGA_PROJECTS_DIR . '/includes/plugin.php' );

function myFoofunction() {
    ladeda();  // defined in plugin.php
}
myFoofunction();
  • 1
    Long story short - always use an absolute filepath. PHP's include/require path resolution is confusing to say the least. If there was a file includes/plugins.php at some point in your includes path (perhaps wp-admin/includes/plugin.php?), that file would've have been included instead. – TheDeadMedic Feb 29 '16 at 10:47
  • 1
    Don't mess with FILE when DIR will get you there faster. Also 'rtrim' is similar to 'untrailingslashit'. – jgraup Feb 29 '16 at 14:58
  • @TheDeadMedic --- this is exactly the answer I was looking for --- thank you. – Denise Draper Mar 4 '16 at 23:03

Relative paths can be confusing in complex applications like WordPress. Plugin files themselves are included by the scripts that call them, and so relative locations within will be interpreted as those of the file that called them.

It's always best practice to provide a full path using a magic constant such as __FILE__ or __DIR__, as you've discovered.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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