3

The real problem I have when using the $wp_filesystem is defining the correct paths. In the documentation of the filesystem the path (for example for the plugins directory) is usually set like this: $plugin_path = str_replace(ABSPATH, $wp_filesystem->abspath(), MY_PLUGIN_DIR);

I tried to understand this but I failed because I couldn't find out what $wp_filesystem->abspath() is actually supposed to return. When I var_dump() it I get false. Could somebody explain to me why we can not simply use the ABSPATH variable in functions like $wp_filesystem->put_contents()?

0

1 Answer 1

1

If you check out the source of abspath():

public function abspath() {
    $folder = $this->find_folder(ABSPATH);
    // Perhaps the FTP folder is rooted at the WordPress install, Check for wp-includes folder in root, Could have some false positives, but rare.
    if ( ! $folder && $this->is_dir( '/' . WPINC ) )
        $folder = '/';
    return $folder;
}

.. you'll see it's main purpose is to get the "calculated" path for the filesystem method. For example, with FTP, the FTP account's root path might be deeper/further down the actual document root. Other methods might also not work with just ABSPATH, hence the find_folder() call (which is actually a wrapper for search_for_folder() which does the real work).

Hence why you've seen something like:

$plugin_path = str_replace(ABSPATH, $wp_filesystem->abspath(), MY_PLUGIN_DIR);

...since MY_PLUGIN_DIR will have been constructed (at some point) based on ABSPATH, but within the context of the filesystem API that path may be invalid - so we replace ABSPATH with the calculated abspath() before writing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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