How to replace file_get_contents() with a WordPress Filesystem call

I’m using the PHP file_get_contents() function to retrieve and echo the contents of an SVG-file.

<?php echo file_get_contents( get_stylesheet_directory_uri() . '/assets/images/Search_Glyph.svg' ); ?>

I checked the theme with the WordPress.org theme checker and I am currently resolving all the issues. One of the issues is the use of file_get_contents.

It gives me the following warning:

WARNING: file_get_contents was found in the file header.php File operations should use the WP_Filesystem methods instead of direct PHP filesystem calls.

I tried finding information about the $wp_filesystem thing, but there is very little information available and even less examples (to be honest, I’m not totally sure if that’s the correct function to use).

How can I use a WordPress function to retrieve a file and echo the contents of it in a PHP-file?

I’m really at loss what I should do with this. All help is very much appreciated!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Firstly add this two line to your functions.php file. Sorry I forgot to mention about this earlier.

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

now you can use WP_Filesystem_Direct::get_contents($path) instead of file_get_contents($path)

Method 2

Solution 01

$wp_filesystem = new WP_Filesystem_Direct(null);
$svg= $wp_filesystem->get_contents(get_stylesheet_directory_uri() . '/assets/images/Search_Glyph.svg');

Solution 02

$remote_svg_file = wp_remote_get(get_stylesheet_directory_uri() . '/assets/images/Search_Glyph.svg');
$svg_content = wp_remote_retrieve_body($remote_svg_file );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x