ShapCyber
ShapCyber

Reputation: 3662

How to delete folder or file in WordPress plugin

I am developing a wordpress plugin which require user to remove (or delete) a directory or file.

After initiating the WP_Filesystem like this

function filesystem_init($form_url, $method, $context, $fields = null) {
global $wp_filesystem;
/* get credentials */
if (false === ($creds = request_filesystem_credentials($form_url, $method, false, $context, $fields))) {
return false;
}

if (!WP_Filesystem($creds)) {
/* incorrect connection data - ask for credentials again, now with error message */
request_filesystem_credentials($form_url, $method, true, $context);
return false;
}
return true; //successfully initiated
}

When the form is posted I have done this to remove a directory with one single file

WP_PLUGIN_DIR.'/myp/mfold/selectedfolder/index.php';

function RemoveData($form_url){
global $wp_filesystem;
check_admin_referer('ToRemoveData');
$ToRemove = $_POST['dirToGo']; 
$form_fields = array('dirToGo');
$method = ''; 
$targetFolder= WP_PLUGIN_DIR . '/myp/mfold/'.$ToRemove; //target folder
$form_url = wp_nonce_url($form_url, 'ToRemoveData'); //page field with nonce value
if(!filesystem_init($form_url, $method, $targetFolder, $form_fields))
return false;
if($wp_filesystem->is_dir($targetFolder))
{   
$wp_filesystem->rmdir($targetFolder);
//WP_Filesystem_Base::delete($targetFolder);        
return " Successful !";
}
else
{
return new WP_Error('writing_error', 'Cannot Remove');
}//return error object
}//close function

This function return Success but the folder or the directory is not deleting.

Any idea anyone Thanks

Upvotes: 1

Views: 3862

Answers (1)

Nitin Sharma
Nitin Sharma

Reputation: 197

$wp_filesystem->delete($target_folder, true);

Use this code to remove directory.

Upvotes: 2

Related Questions