Last active
March 9, 2016 19:42
-
-
Save sidati/2f39c767e05d8fdc776a to your computer and use it in GitHub Desktop.
WP File System Helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
private static function wp_filesystem_init($form_url, $context, $fields) { | |
if (!function_exists('request_filesystem_credentials')) { | |
load_template(ABSPATH.'wp-admin/includes/file.php'); | |
} | |
if ((!is_admin() && 'direct' !== get_filesystem_method(null, $context)) || | |
false === ($creds = request_filesystem_credentials($form_url, null, false, false, $fields))) { | |
return false; | |
} | |
if (!WP_Filesystem($creds)) { | |
request_filesystem_credentials($form_url, null, false, $context, $fields); | |
return false; | |
} | |
return true; | |
} | |
static function file_handler($form_url, $path, $action = 'read', $data = null) { | |
global $wp_filesystem; | |
if (!in_array($action, array('write', 'read', 'delete')) || ('write' === $action && empty($data))) { | |
return false; | |
} | |
$form_fields = null; | |
if (!empty($data)) { | |
$form_fields = array('data'); | |
} | |
$pathinfo = pathinfo($path); | |
$context = $pathinfo['dirname']; | |
$filename = $pathinfo['basename']; | |
$form_url = wp_nonce_url($form_url, 'prefix-'.$action); | |
if (!self::wp_filesystem_init($form_url, $context, $form_fields)) { | |
return false; | |
} | |
if (!$wp_filesystem->exists($context)) { | |
$wp_filesystem->mkdir($context, 0775); | |
} | |
$target_dir = $wp_filesystem->find_folder($context); | |
$target_file = trailingslashit($target_dir).'/'.$filename; | |
switch ($action) { | |
case 'read': | |
if ($wp_filesystem->exists($target_file)) { | |
if (!$output = $wp_filesystem->get_contents($target_file)) { | |
return false; | |
} | |
return $output; | |
} | |
break; | |
case 'delete': | |
if ($wp_filesystem->exists($target_file)) { | |
return $wp_filesystem->delete($target_file); | |
} | |
break; | |
case 'write': | |
if (!$wp_filesystem->put_contents($target_file, $data)) { | |
return false; | |
} | |
break; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment