I'm trying to read a .txt file using WP_Filesystem_Direct
and I don't know what I am doing wrong. This is the error on the last line of the code at $filesystem
:
Uncaught Error: Object of class WP_Filesystem_Direct could not be converted to string
In functions.php
global $wp_filesystem;
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
In page template:
$filesystem = new WP_Filesystem_Direct( false );
$server = getcwd();
$path = $server . '/wp-content/uploads/on_this_day.txt';
$filesystem->get_contents($path);
echo $filesystem;
The $path
to the file is correct and the file opens in a browser when directly accessed.
var_dump($filesystem);
shows
object(WP_Filesystem_Direct)#2990 (5) { ["verbose"]=> bool(false) ["cache"]=> array(0) { } ["method"]=> string(6) "direct" ["errors"]=> object(WP_Error)#3047 (3) { ["errors"]=> array(0) { } ["error_data"]=> array(0) { } ["additional_data":protected]=> array(0) { } } ["options"]=> array(0) { } }
I'm trying to read a .txt file using WP_Filesystem_Direct
and I don't know what I am doing wrong. This is the error on the last line of the code at $filesystem
:
Uncaught Error: Object of class WP_Filesystem_Direct could not be converted to string
In functions.php
global $wp_filesystem;
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
In page template:
$filesystem = new WP_Filesystem_Direct( false );
$server = getcwd();
$path = $server . '/wp-content/uploads/on_this_day.txt';
$filesystem->get_contents($path);
echo $filesystem;
The $path
to the file is correct and the file opens in a browser when directly accessed.
var_dump($filesystem);
shows
Share Improve this question asked Feb 6 at 1:46 BlueDogRanchBlueDogRanch 1745 silver badges25 bronze badgesobject(WP_Filesystem_Direct)#2990 (5) { ["verbose"]=> bool(false) ["cache"]=> array(0) { } ["method"]=> string(6) "direct" ["errors"]=> object(WP_Error)#3047 (3) { ["errors"]=> array(0) { } ["error_data"]=> array(0) { } ["additional_data":protected]=> array(0) { } } ["options"]=> array(0) { } }
1 Answer
Reset to default 1In here:
$filesystem = new WP_Filesystem_Direct( false );
$server = getcwd();
$path = $server . '/wp-content/uploads/on_this_day.txt';
$filesystem->get_contents($path);
echo $filesystem;
...note that $filesystem
, in the last line, is the same variable that's holding your WP_Filesystem
object. Try this instead:
$filesystem = new WP_Filesystem_Direct( false );
$server = getcwd();
$path = $server . '/wp-content/uploads/on_this_day.txt';
$file_content = $filesystem->get_contents($path);
echo $file_content;