Skip to content

Instantly share code, notes, and snippets.

@ramonamorea
Last active May 5, 2018 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramonamorea/573b6419d0da7746e985eeb949e200ca to your computer and use it in GitHub Desktop.
Save ramonamorea/573b6419d0da7746e985eeb949e200ca to your computer and use it in GitHub Desktop.
WP_Filesystem example
class WP_Custom_Writer {
/**
* Stores the initialized WordPress filesystem.
*
* @access private
* @var WP_Filesystem
*/
private $file_system;
/**
* Class constructor.
*
* @global WP_Filesystem_Base $wp_filesystem
* @access public
*/
public function __construct() {
// Start initiating filesystem.
global $wp_filesystem;
$url = wp_nonce_url( admin_url( 'tools.php?page=your_page'), 'your_text_domain' );
// Get filesystem credentials needed for WP_Filesystem.
$creds = request_filesystem_credentials( $url, '', false, false, null );
if ( false === $creds ) {
_e( 'Credentials are required to save the file.', 'your_text_domain' );
exit();
}
// Get the upload directory.
$wp_upload_dir = wp_upload_dir();
// When credentials are obtained, check to make sure they work.
if ( ! WP_Filesystem( $creds, $wp_upload_dir['basedir'] ) ) {
// Request_filesystem_credentials a second time, but this time with the $error flag set.
request_filesystem_credentials( $url, '', true, false, null );
_e( 'Credentials are required to save the file', 'your_text_domain' );
exit();
}
// Populate class private members with what was obtained.
$this->file_system = $wp_filesystem;
//..other code here
// Then, in other methods, you just use similar to this:
$this->file_system->mkdir( "your_folder_name" );
// Or you can write to a file.
global $wp_filesystem;
$this->file_system->put_contents(
'/tmp/example.txt',
'Example contents of a file',
FS_CHMOD_FILE // predefined mode settings for WP files
);
// MORE INFO HERE: https://codex.wordpress.org/Filesystem_API
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment