Skip to content

Instantly share code, notes, and snippets.

@trey8611
Created January 8, 2022 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trey8611/f37a381f138ad32c3fda737d073d0c12 to your computer and use it in GitHub Desktop.
Save trey8611/f37a381f138ad32c3fda737d073d0c12 to your computer and use it in GitHub Desktop.
[Upload embedded media to WordPress Media Library] #phpexcel

This snippet uploads all images embedded in the import file to the WordPress Media Library. Hat tip to https://stackoverflow.com/a/10910199 for the code inspiration.

add_filter( 'wp_all_import_phpexcel_object', 'wpai_wp_all_import_phpexcel_object', 10, 2 );

function wpai_wp_all_import_phpexcel_object( $objPHPExcel, $xlsFilePath ) {
    $i = 0;
    foreach ($objPHPExcel->getActiveSheet()->getDrawingCollection() as $drawing) {
        if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
            ob_start();
            call_user_func(
            $drawing->getRenderingFunction(),
            $drawing->getImageResource()
            );
            $imageContents = ob_get_contents();
            ob_end_clean();
            
            switch ($drawing->getMimeType()) {
                case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
                    $extension = 'png'; break;
                case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
                    $extension = 'gif'; break;
                case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
                    $extension = 'jpg'; break;
            }
        } else {
            $zipReader = fopen($drawing->getPath(),'r');
            $imageContents = '';
            while (!feof($zipReader)) {
                $imageContents .= fread($zipReader,1024);
            }
            fclose($zipReader);
            $extension = $drawing->getExtension();
        }
        $uploads = wp_upload_dir();
        
        $myFileName = $uploads['basedir'] . '/00_Image_'.++$i.'.'.$extension;
        file_put_contents($myFileName,$imageContents);
        
        $url = $uploads['baseurl'] . '/' . basename( $myFileName );
        $upload_to_medalibrary = PMXI_API::upload_image( 0, $url, 'yes', false, true );
        unlink ( $myFileName );
    }
    
    return $objPHPExcel;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment