Using wp_filesystem in Plugins

Few things to explain here:

In that tutorial, I only chose the upload_dir as an example of how to do it. A demonstration of how the WP_Filesystem functions work. Normally you would not use the WP_Filesystem to write to the upload directory. That code is not meant to be copy-pasta’d into live production code.

Writing CSS, PHP, HTML, or really any other kind of files except images into the upload directory… and which will then be included in the web page in some fashion, is unsafe.

Doesn’t really matter how you do it, the upload directory is expected to contain things that are not considered necessarily XSS safe by its very nature. If you need to write files to be included in the page, like stylesheets, then you should make your own folder under /wp-content, not under /wp-content/uploads. The uploads directory should be used strictly for media files and downloads and other things uploaded through the various wp_upload functions.

When using the $wp_filesystem, there’s a handy function call for getting the content directory path: $wp_filesystem->wp_content_dir();. You need to use this function because the “remote” directory path may not be the same as the “local” directory path.

There is not a similar function for getting the uploads_dir, because again, you normally would never do that. Really doesn’t make a lot of sense to use the uploads dir for those files.

So, this will give you the “remote” path to the content directory, and you can use it to write files and make directories and such like so:

$contentdir = trailingslashit( $wp_filesystem->wp_content_dir() ); 
$wp_filesystem->mkdir( $contentdir. 'cbe' );
$wp_filesystem->put_contents( $contentdir . 'cbe/filename.whatever', $css, FS_CHMOD_FILE);

And so forth. Of course, you still need to request the credentials and instantiate with the WP_Filesystem($creds) call first to use that global $wp_filesystem, but this works.

Leave a Comment