How to replace file_get_contents() with a Wordpress Filesystem call
-
20-04-2021 - |
Pregunta
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!
Solución
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)
Otros consejos
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 );