我有一个控制台脚本,可以导入woocommerce产品,并为产品创建图像和缩略图。
问题是缩略图被裁剪了。我需要压缩所有生成的缩略图以保持原始图像。
用于将图像放入数据库和服务器的函数:
private function generateFeaturedImage($imageUrl, $postId, $isCategory = false)
{
$imageUrl = $this->escapefileUrl($imageUrl);
$imageUrl = str_replace("%26", "&", $imageUrl);
$uploadDir = wp_upload_dir();
$filename = str_replace("%20", "-", basename($imageUrl));
if(wp_mkdir_p($uploadDir[\'path\'])) {
$file = $uploadDir[\'path\'] . \'/\' . $filename;
} else {
$file = $uploadDir[\'basedir\'] . \'/\' . $filename;
}
file_put_contents($file, file_get_contents($imageUrl));
$fileType = wp_check_filetype($filename, null );
$attachment = array(
\'post_mime_type\' => $fileType[\'type\'],
\'post_title\' => sanitize_file_name($filename),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$attachId = wp_insert_attachment( $attachment, $file, $postId );
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$attachData = wp_generate_attachment_metadata( $attachId, $file );
wp_update_attachment_metadata( $attachId, $attachData );
set_post_thumbnail( $postId, $attachId );
}