在 WooCommerce 中按类别导入产品

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

我几周来一直在尝试从 csv 或 xml 导入产品。我可以导入标题价格 sku 图像等数据,但无法导入类别。既不能单独使用,也不能与相同功能一起使用

function import_products_from_csv() {
    // Path of the CSV file on your server
    $local_file_path = WP_CONTENT_DIR . '/../products.csv';

$args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
    );

    $products = get_posts($args);

    // Delete each product
    foreach ($products as $product) {
wp_delete_post($product->ID, true); // The second parameter (true) will force the permanent deletion of the product.
    }

    // Check if the CSV file exists
    if (file_exists($local_file_path)) {
        // Open the CSV file for reading
        if (($handle = fopen($local_file_path, 'r')) !== false) {
// Ignore the first row (header)
            $header = fgetcsv($handle, 1000, ';');

            while (($data = fgetcsv($handle, 1000, ';')) !== false) {
                // Create a new product in WooCommerce
                $product = array(
                    'post_title' => $data[1],
// Adjust the position according to your CSV file
                   // 'post_content' => $data[2], // Adjust the position according to your CSV file
                  // 'post_excerpt' => $data[3], // Adjust the position according to your CSV file
'post_type' => 'product',
                    'post_status' => 'publish',
                );
$product_id = wp_insert_post($product);

// Assign SKU and price to the product
if ($product_id) {
update_post_meta($product_id, '_sku', $data[0]); // Adjust the position according to your CSV file
update_post_meta($product_id, '_regular_price', $data[2]); // Adjust the position according to your CSV file
update_post_meta($product_id, '_price', $data[2]);
// Force product cache refresh
wp_cache_delete($product_id, 'post_meta');
}


                // Assign categories to the product
             if (!empty($data[4])) {
$categories = explode(',', $data[4]);
//$result = wp_set_post_terms($product_id, $categories, 'productcategory');
//$result = wp_set_post_terms($product_id, $categories, 'product_cat');
$result = wp_set_object_terms($product_id, $categories, 'productcategory');
    
//var_dump($categories); // Verify that $categories has the expected categories.
//var_dump($product_id); // Verify that $product_id has the correct product ID.


/*if (taxonomy_exists('Pillows')) {
// The 'productcategory' taxonomy exists, you can use it in your code.
$result = wp_set_object_terms($product_id, $categories, 'Pillows');
} else {
// The taxonomy 'productcategory' does not exist, display an error message, or take the appropriate action.
echo 'The taxonomy "pillows" is not registered.';
}

if (is_wp_error($result)) {
echo 'Error assigning categories: ' . $result->get_error_message();
} else {
echo 'Categories assigned correctly.';
}*/
}

//
 if (!empty($data[3])) { // Adjust the position according to your CSV file
    $image_url = $data[3]; // Adjust the position according to your CSV file

    // Calculate a unique hash based on the image URL
    $image_hash = md5($image_url);

    // Search for an image with the same hash in the media library
$image_query = new WP_Query(array(
        'post_type' => 'attachment',
        'post_status' => 'any',
        'posts_per_page' => 1,
        'meta_query' => array(
            array(
                'key' => 'hash_image',
                'value' => $image_hash,
            ),
        ),
    ));

    if ($image_query->have_posts()) {
// The image already exists in the media library
        $image_id = $image_query->posts[0]->ID;
    } else {
        // The image does not exist in the media library, proceed to import it

        // Get the file name from the URL
        $file_name = basename($image_url);
// Local path where to save the image in the 'uploads' folder
        $local_path = wp_upload_dir()['path'] . '/' . $file_name;

        // Download the image from the URL and save it to the 'uploads' folder
        $image_content = file_get_contents($image_url);

        if ($content_image !== false) {
file_put_contents($local_path, $content_image);

            // Add the image to the media library
            $attachment = array(
                'post_title' => sanitize_file_name($file_name),
                'post_mime_type' => wp_check_filetype($file_name)['type'],
                'post_status' => 'inherit'
);

            $image_id = wp_insert_attachment($attachment, $local_path);

            if (!is_wp_error($image_id)) {
                // Generate metadata and update attachment information
                require_once(ABSPATH . 'wp-admin/includes/image.php');
$image_metadata = wp_generate_attachment_metadata($image_id, $local_path);
                wp_update_attachment_metadata($image_id, $image_metadata);

                // Associate the unique hash to the image
                update_post_meta($image_id, 'image_hash', $image_hash);
            } else {
echo "Error adding image to media library: " . $image_id->get_error_message();
            }
        } else {
            echo "Error downloading image from URL: " . $image_url;
        }
    }
// Assign the uploaded image (either existing or newly imported) to your product (adjust $product_id as necessary)
    set_post_thumbnail($product_id, $image_id);
}




            }

            fclose($handle);
            echo "Products successfully imported from CSV.";
        } else {
echo "Error opening CSV file.";
        }
    } else {
        echo "CSV file does not exist.";
    }
}

// Call the function to import products from CSV if any condition is met (you can define it according to your needs)
if (isset($_GET['import_products']) && $_GET['import_products'] == '1') {
import_products_from_csv();
}

我留下了评论尝试,所以你知道我想去哪里。 我希望知道要遵循的步骤是什么,如果我必须将其分为几个阶段,或者我可以在同一个函数中完成

php wordpress woocommerce import product
1个回答
1
投票

开始之前

  • 确保您的 WordPress 网站上安装并激活了 WooCommerce。 准备您的产品数据。
  • WooCommerce 支持 CSV 文件导入。您的 CSV 文件应包含产品详细信息,例如名称、描述、价格、类别等。

按类别导入产品的分步指南

  1. 准备您的 CSV 文件
  • 您的 CSV 文件必须包含所有产品信息的列, 包括产品类别。

  • 对于类别,您可以通过以下方式为产品分配多个类别 用逗号分隔它们。如果您使用分层类别 (子类别),您可以使用 > 来指定它们以表示级别。为了 例如,服装 > 男士 > 衬衫。

  • 确保列标题与字段 WooCommerce 匹配 期望。您可以找到示例 CSV 文件和所有支持的列表 WooCommerce 文档中的专栏。

  1. 访问进口商
  • 在 WordPress 仪表板中,转到产品 > 所有产品。

  • 产品列表上方有一个导入按钮。单击它开始 导入过程。

  1. 上传您的 CSV 文件
  • 单击选择文件并从计算机中选择 CSV 文件。后 选择您的文件,单击继续。

  • WooCommerce 将尝试自动匹配 CSV 中的列名称 到产品领域。检查这些映射以确保它们正确。 如果 WooCommerce 没有自动正确匹配列,您 可以使用下拉菜单手动调整。

  1. 运行导入器
  • 正确映射所有列后,单击“运行导入器”。

  • WooCommerce 将开始从您的 CSV 文件导入产品。这 该过程可能需要一些时间,具体取决于产品的数量。

  • 导入完成后,您将看到一条成功消息。

  1. 顺利导入的技巧
  • 首先测试一些产品:在导入整个目录之前, 尝试导入少量产品以确保一切正常 正如预期的那样。

  • 检查您的类别:确保 CSV 文件中的类别 与 WooCommerce 中的类别匹配。如果某个类别不存在, WooCommerce 应该自动创建它,但最好的做法是 提前设置好您的类别结构。

  • 备份您的数据:在执行批量操作之前,请务必备份您的网站 业务,包括产品进口。这确保您可以恢复 如果出现任何问题,您的网站将恢复到之前的状态。


此方法应该可以满足大多数分类导入产品的需求。如果您有更复杂的需求,例如导入自定义字段或处理非常大的数据集,您可以探索插件解决方案,例如 WP All Import 或编写自定义脚本。


© www.soinside.com 2019 - 2024. All rights reserved.