Question

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()?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top