UNZIP_FILE导致媒体文件上载错误

时间:2019-04-26 作者:Troy Templeman

当我尝试使用unzip_file 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!\';       
}
在中尝试将任何文件上载到媒体库时,出现以下错误Media > Add New:

An error occurred in the upload. Please try again later.
我使用的是2019主题,没有激活插件。当我删除函数时,我没有得到错误。

有什么想法吗?

2 个回复
SO网友:Troy Templeman

通过在内部使用它,我使它能够正常工作add_attachment 钩子下面,但现在的问题是它运行在每一个媒体上传。

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\' );
我尝试将其限制在下面的特定自定义程序文件上载中,但它根本不起作用。

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\' );
我错过什么了吗?

SO网友:Andre Gagnon

我知道这可能有点旧,但在获得\\u attached\\u文件后,可以检查扩展名的路径(https://www.php.net/manual/en/function.pathinfo.php):

<?php

$file_path = get_attached_file( $post_ID );
$path_parts = pathinfo($file_path);

// do nothing if not zip
if ( path_parts[\'extension\'] !== \'zip\' ) {
   return;
}
     
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);