简体   繁体   中英

Converting fopen/fwrite to WordPress WP_Filesystem

I'm using code from the Easy Theme Child plugin in my theme, but it fails the Theme Check plugin with the following error:

WARNING: fopen/fwrite was found in the file grtsth-easy-child-theme-resources.php and resources.php File operations should use the `WP_Filesystem` methods instead of direct PHP filesystem calls.

So I tried converting the problem code:

$create_style_css    = fopen( $file_style_css, 'w+' );
$create_function_php = fopen( $file_function_php, 'w+' );
fwrite( $create_style_css, $stylesheet_data );
fwrite( $create_function_php, $function_php_data );

to:

WP_Filesystem();
global $wp_filesystem;

$create_style_css    = $wp_filesystem->get_contents($file_style_css);
$create_function_php = $wp_filesystem->get_contents($file_function_php);
$wp_filesystem->put_contents($create_style_css, $stylesheet_data);
$wp_filesystem->put_contents($create_function_php, $function_php_data);

However, its not working. No errors. Just not creating the child theme files. I'm not very familiar with WP_Filesystem , so any ideas what I'm doing wrong?

Thanks

(this is more of a comment than an answer - can't comment yet!)

This is a warning that, for many users, you can ignore. Your theme will continue to function fine.

The warning is just saying that the theme is reading/writing files as the webserver user, where as the WP Filesystem could utilise other methods of file operations, which are beneficial in some situations.

I wouldn't bother trying to change the read/write ops to WP Filesystem, especially if you're not planning on deploying your code to a wide range of environments (I assume you are just talking about one website).

BUT, if you really wanted to proceed...

You need to set / get access Credentials , before proceeding with file operations.

See this handy step-by-step guide: https://www.sitepoint.com/introduction-to-the-wordpress-filesystem-api/

You need to include the wp_filesystem functions first and also to request credentials (if the wp_filesystem object was not used before). Check the code from below for details:

global $wp_filesystem;
if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
    include_once(ABSPATH . 'wp-admin/includes/file.php');
    $creds = request_filesystem_credentials( site_url() );
    wp_filesystem($creds);
}
$create_style_css = $wp_filesystem->get_contents($url);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM