0

When I attempt to use the unzip_file function below in my functions.php:

require_once(ABSPATH . 'wp-admin/includes/file.php');
WP_Filesystem();
$destination = wp_upload_dir();
$destination_path = $destination['path'];
$unzipfile = unzip_file( $destination_path.'/filename.zip', $destination_path);

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

I get the following error when trying to upload any files into the Media library in Media > Add New:

An error occurred in the upload. Please try again later.

I am using Twenty Nineteen theme with no plugins activated. I don't get the error when I remove the function.

Any ideas?

  • 1
    How exactly do you "use" it? What's the actual code in your functions.php file? – Sally CJ Apr 26 '19 at 3:09
  • It's being used and included in functions.php exactly as above. There is a filename.zip file in my uploads folder, which gets unzipped into the same folder as it should. The only problem is uploading media files while this function is in place. – Troy Templeman Apr 26 '19 at 10:14
  • You should run the code only when necessary and from the right "place". Did you put it inside a function? And did you hook it to an action like init? E.g. add_action( 'init', function(){ if ( expression ) { // run your code } } ); – Sally CJ Apr 26 '19 at 16:13
  • Yes, I already tried it inside a function on init with the same result. – Troy Templeman Apr 26 '19 at 21:09
0

I got it to work without errors by using it inside add_attachment hook below, but now the problem is it runs on every media upload.

function unzip_icon_fonts( $post_ID ){
    $file_path = get_attached_file( $post_ID );
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    WP_Filesystem();
    $destination = wp_upload_dir();
    $destination_path = $destination['path'];
    $unzipfile = unzip_file($file_path, $destination_path); 
}
add_action( 'add_attachment', 'unzip_icon_fonts' );

I tried restricting it to a specific Customizer file upload below, but then it doesn't work at all.

function unzip_icon_fonts( $post_ID ){
    // If attachment ID equals Customizer file upload ID added with WP_Customize_Media_Control
    if ( $post_ID == get_theme_mod('icon_fonts', '') ) {
        $file_path = get_attached_file( $post_ID );
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        WP_Filesystem();
        $destination = wp_upload_dir();
        $destination_path = $destination['path'];
        $unzipfile = unzip_file($file_path, $destination_path); 
    }
}
add_action( 'add_attachment', 'unzip_icon_fonts' );

Am I missing something?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.