Created
November 7, 2013 08:08
-
-
Save thanh4890/7350866 to your computer and use it in GitHub Desktop.
WordPress Filesystem Tutorial
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 | |
/* | |
Plugin Name: Filesystem Tutorial | |
Description: Demo Plugin for http://ottopress.com/2011/tutorial-using-the-wp_filesystem | |
Plugin URL: http://ottopress.com/2011/tutorial-using-the-wp_filesystem | |
Author: otto42 | |
DO NOT USE THIS ON A PRODUCTION SITE. THIS IS DEMONSTRATION CODE ONLY. | |
*/ | |
// add the admin options page | |
add_action('admin_menu', 'otto_admin_add_page'); | |
function otto_admin_add_page() { | |
add_theme_page('Otto Test Page', 'Otto Test Options', 'edit_theme_options', 'otto', 'otto_options_page'); | |
} | |
function otto_options_page() { | |
if ( otto_check_buttons() ) return; | |
?> | |
<div> | |
<h2>My custom options page</h2> | |
<form action="" method="post"> | |
<?php wp_nonce_field(); ?> | |
<input name="save" type="submit" value="Save a file" /> | |
</form></div> | |
<?php | |
} | |
function otto_check_buttons() { | |
if (empty($_POST)) return false; | |
check_admin_referer(); | |
$form_fields = array ('save'); // this is a list of the form field contents I want passed along between page views | |
$method = ''; // Normally you leave this an empty string and it figures it out by itself, but you can override the filesystem method here | |
// check to see if we are trying to save a file | |
if (isset($_POST['save'])) { | |
// okay, let's see about getting credentials | |
$url = wp_nonce_url('themes.php?page=otto'); | |
if (false === ($creds = request_filesystem_credentials($url, $method, false, false, $form_fields) ) ) { | |
// if we get here, then we don't have credentials yet, | |
// but have just produced a form for the user to fill in, | |
// so stop processing for now | |
return true; // stop the normal page form from displaying | |
} | |
// now we have some credentials, try to get the wp_filesystem running | |
if ( ! WP_Filesystem($creds) ) { | |
// our credentials were no good, ask the user for them again | |
request_filesystem_credentials($url, $method, true, false, $form_fields); | |
return true; | |
} | |
// get the upload directory and make a test.txt file | |
$upload_dir = wp_upload_dir(); | |
$filename = trailingslashit($upload_dir['path']).'test.txt'; | |
// by this point, the $wp_filesystem global should be working, so let's use it to create a file | |
global $wp_filesystem; | |
if ( ! $wp_filesystem->put_contents( $filename, 'Test file contents', FS_CHMOD_FILE) ) { | |
echo "error saving file!"; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment