1

I am writing a plugin. I wrote this function to create a custom directory in the root.

function create_api_dir() {

    $upload = wp_upload_dir();
    //$upload_dir = $upload['basedir'];
    $upload_dir = $_SERVER['DOCUMENT_ROOT'];
    $upload_dir = $upload_dir . '/api';
    if (! is_dir($upload_dir)) {
       mkdir( $upload_dir, 0700 );
    }
}

register_activation_hook( __FILE__, 'create_api_dir' );

This function is creating a folder named api in the root server.

Now my plugin also consists of a folder with same name api with files inside this. I want to allow users to import the entire folder (unpacked) to that api folder OR have them uploaded to the api folder on plugin activation.

How I can achieve this?

Thanks

Ayanize
  • 485
  • 1
  • 4
  • 21

1 Answers1

0

I found a workaround. Please advise if that's okay to implement. Instead of copying folders and its sub-folders I zipped the entire folderapi.zip.Now following the thread here I applied those two function. One to copy the file and another to unzip this in the destination. Here are they.

/*....function to copy the zip file...*/

function recurse_copy($src,$dst = 0) {
    $src = plugin_dir_path( __FILE__ ) . 'api';
    $dst = $_SERVER['DOCUMENT_ROOT'] . '/api';
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}


add_action('plugins_loaded', 'recurse_copy', 10, 2);

/*...function to unzip the file in the destination ....*/

function unzip_api(){

WP_Filesystem();
$destination = $_SERVER['DOCUMENT_ROOT'] . '/api';
$destination_path = $_SERVER['DOCUMENT_ROOT'] . '/api';
$unzipfile = unzip_file( $destination_path.'/api.zip', $destination_path);

   if ( $unzipfile ) {
      echo 'Successfully unzipped the file!';       
   } else {
      echo 'There was an error unzipping the file.';       
   }

}
add_action('admin_init', 'unzip_api');
Community
  • 1
  • 1
Ayanize
  • 485
  • 1
  • 4
  • 21