woocommerce 产品图片以编程方式上传/导入

问题描述 投票:0回答:1

您好使用以下代码将产品图片上传/导入到我的 woocommerce 网站。它的工作原理是将图像上传到服务器并生成缩略图。所以文件路径就在那里。我遇到的问题是图像没有显示在管理媒体库中,它显示默认图像占位符。我就是不明白为什么。并且图像也不会显示在图像下方。即使它通过 wp_post 和 wp_postmeta 链接到产品

这是我用来上传/导入图像的代码

// Define batch size and other variables
$batch_size = 200;
$total_products = $wpdb->get_var("SELECT COUNT(*) FROM products_images");
$total_batches = ceil($total_products / $batch_size);

// Loop through batches
for ($batch_number = 1; $batch_number <= $total_batches; $batch_number++) {
    $offset = ($batch_number - 1) * $batch_size;
    $woo_products_images = $wpdb->get_results("SELECT * FROM `products_images` WHERE strPartNumber='BA212120' LIMIT $offset, $batch_size");

    // Load WordPress media handling functions
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');

    foreach ($woo_products_images as $woo_products_image) {
        $imageID = $woo_products_image->Image_ID;
        $bitDefaultImage = $woo_products_image->bitDefaultImage;
        $strPartNumber = $woo_products_image->strPartNumber;
        $imgData = base64_encode($woo_products_image->imgData);
        $imageData = base64_decode($imgData);

        // Check if the attachment already exists based on the image URL
        $existing_attachment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE guid = %s", $imageURL));
        if (!$existing_attachment) {
            // Image doesn't exist, insert it as a new attachment
            $imageFile = wp_upload_bits($strPartNumber . '_' . $imageID . '.jpg', null, $imageData);
            if (!$imageFile['error']) {
                // Image uploaded successfully, get its URL and attachment ID
                $imageURL = $imageFile['url']; // Correctly set the image URL
                echo "Image URL after upload: $imageURL<br>"; // Add this line to check image URL after upload
                $attachment_id = attachment_url_to_postid($imageURL);

                // Set the post date and post date GMT
                $current_date = current_time('mysql');
                $insert_data = array(
                    'post_author' => 4,
                    'post_title' => $strPartNumber . ' ' . $imageID,
                    'post_status' => 'inherit',
                    'post_name' => $strPartNumber . '_' . $imageID,
                    'post_parent' => 0,
                    'guid' => $imageURL,
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image/jpeg',
                    'post_date' => $current_date,
                    'post_date_gmt' => get_gmt_from_date($current_date)
                );

                $wpdb->insert($wpdb->posts, $insert_data);
                $attachment_id = $wpdb->insert_id;

                // Generate image metadata (thumbnails)
                $metadata = wp_generate_attachment_metadata($attachment_id, $imageFile['file']);
                wp_update_attachment_metadata($attachment_id, $metadata);
            } else {
                echo "Error uploading image: " . $imageFile['error'];
            }
        } else {
            // Image already exists, use existing attachment ID
            $attachment_id = $existing_attachment->ID;
            $imageURL = wp_get_attachment_url($attachment_id); // Update the image URL
            echo "Image URL already exists: $imageURL<br>"; // Add this line to check existing image URL
        }

        // Link image to product
        $productId = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $strPartNumber));

        if ($productId) {
            // Set the image as the featured image for the product
            set_post_thumbnail($productId, $attachment_id);
            echo "Image (ID: $attachment_id) linked to product with SKU: $strPartNumber - product ID: $productId<br>";
        } else {
            echo "Product not found with SKU: $strPartNumber<br>";
        }
    }
}

我解释说,当我以编程方式导入/上传图像时,所有图像都应该显示,但没有显示

php wordpress woocommerce
1个回答
0
投票

缺少

$imageURL
变量初始化

您在赋值之前引用

$imageURL
。在循环外将其初始化为空字符串以避免潜在的错误:

$imageURL = '';

使用

wp_upload_bits
media_handle_upload

虽然

wp_upload_bits
有效,但请考虑使用
media_handle_upload
在 WordPress 中实现更简化的方法

$upload = media_handle_upload( $strPartNumber . '_' . $imageID . '.jpg', null, $imageData );
if ( ! isset( $upload['error'] ) ) {
    $imageURL = $upload['url'];
    echo "Image URL after upload: $imageURL<br>";
} else {
    echo "Error uploading image: " . $upload['error'];
}
© www.soinside.com 2019 - 2024. All rights reserved.