I need to obtain a reference to the $wp_filesystem object. In the test below, the var_dump($wp_filesystem) returns NULL. What additional files are required in order to properly set up $wp_filesystem?
I was expecting that since its called in file.php, loading that file would be sufficient to load the object.
<?php
require('../../../wp-blog-header.php');
require('../../../wp-admin/includes/file.php');
$mytest = somefunction();
function somefunction() {
global $wp_filesystem;
var_dump($wp_filesystem);
return;
}
?>
UPDATE: I’ve found that I can call WP_Filesystem() directly to create it, so I’m getting the zip extracted fine, now the problem is that the zip file is copied to the destination folder rather than deleted as my ZipArchive method does.
require('../../../wp-blog-header.php');
require('../../../wp-admin/includes/file.php');
function openZip($file_to_open) {
global $target;
global $wp_filesystem;
if(class_exists('ZipArchive'))
{
$zip = new ZipArchive();
$x = $zip->open($file_to_open);
if($x === true)
{
$zip->extractTo($target);
$zip->close();
unlink($file_to_open);
} else {
die("There was a problem. Please try again!");
}
}
else
{
WP_Filesystem();
$my_dirs = ''; //What should this be? I'm already passing he $target directory
_unzip_file_pclzip($file_to_open, $target, $my_dirs);
}
}
$wp_filesystem
is a global variable containing the instance of the (auto-)configured filesystem object after the filesystem “factory” has been run.To run the factory “over” the global variable (so to set it), just call the
WP_Filesystem()
function which is, guess what, undocumented in codex. At least the docblock contains some information and you can read the sourcecode (if that’s an option for you).Anyway, I would give it a try to add a function call to your code after requiring the file.php from the
/wp-admin/includes
directory. Probably this already solves your issue.If you are looking for a (better) file-system abstraction than/next to the built-in one, consider the file-system objects in SPL which is part of PHP already.