Search code examples
phpwordpresspathrequire

WP plugin: Why do I need to require the dependencies of a library?


In a WordPress plugin, this does NOT work

<?php

/**
 * Plugin Name:       test
 * Plugin URI:        _
 * Description:       _
 * Version:           0.0.1
 * Author:            _
 * Author URI:        _
 * License:           GPL-2.0+
 * License URI:       _
 * Text Domain:       _
 */


// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';

But this DOES work

require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';

Where inside class-wp-filesystem-direct you can see that it extends from class-wp-filesystem-base

Why do I need to require the two libraries?


The error was

Fatal error: Uncaught Error: Class 'WP_Filesystem_Base' not found in /home/..../domains/..../public_html/wp-admin/includes/class-wp-filesystem-direct.php:16 

Solution

  • The require statement works exactly as it's supposed to, the problem is what you're loading in. It has dependencies that are unmet, and depends on other things that aren't loaded.

    Loading class-wp-filesystem-direct.php will load the things in that file, but it won't go searching for other things it needs. WordPress doesn't use PHP autoloading

    So some notes:

    • WP Admin include files in WordPress don't contain all their dependencies
    • If you try to load a class that inherits from a class that hasn't been loaded, you'll get a fatal error
    • You shouldn't be trying to include WP Admin files at the top of your plugin, it can cause issues by loading on the frontend
    • If you want to work with WP_FileSystem you don't need to load those files and folders

    Your problem is that you can't just include random files in WP Admin, they have dependencies that need to be included beforehand.

    So your require statement works fine,