以编程方式批量创建 WooCommerce 产品

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

可以在 WooCommerce 上批量创建产品吗? 我正在使用 wp-cli Product 命令,但似乎我必须一一创建。

<?php

$products = array(
    array('title' => 'My product 1'),
    array('title' => 'My product 2'),
    // ...
    // 10.000 more products
);

foreach ($products as $product) {
    $cliProduct = new WC_CLI_Product();
    $cliProduct->create(array(), $product);
    WP_CLI::success("Added Product #{$product['title']}");
}

这需要花费大量时间,因为它将对每个产品进行查询,更糟糕的是,这将是一个定期运行的 cron 作业。我还必须检查该产品是否存在,在这种情况下,更新它而不是创建新产品。

因此查询数量将乘以2。

产品存在吗?更新它,否则创建它

有更好的方法吗? 也许我应该直接查询数据库,但它看起来很脏。

是否有任何 WP 功能可以查询数据库而无需创建自己的数据库连接?

php wordpress woocommerce wp-cli
3个回答
6
投票

我早在 2017 年就写过这个答案,当时 WooCommerce 版本低于 < 3.0. So 如果您使用的是 WooCommerce 3.0 版。那么请参考这个答案

截至 2022 年 3 月,此答案仍然有效,但 我建议使用此答案 > v3.0。

假设您有一个像这样的数组,并且您有 Unique

SKU
来识别产品。

$products = [
    0 => [
        'title' => 'My Simple product 1',
        'sku' => 'sku1',
        'product_cat' => 'My cat'
    //...
    //...
    ],
    1 => [
        'title' => 'My Simple product 1',
        'sku' => 'sku1'
    //...
    //...
    ]
];

通过

myCustomProduct()
方法传递上面的数组。

function myCustomProduct($product_array)
{
    if (!empty($product_array)):
        foreach ($product_array as $product):
            $product_id = wc_get_product_id_by_sku($product['sku']);
            //no product exist with the given SKU so create one
            if (!$product_id):
                $post = [
                    'post_author' => '',
                    'post_content' => $product['content'],
                    'post_status' => "publish",
                    'post_title' => wp_strip_all_tags($product['title']),
                    'post_name' => $product['title'],
                    'post_parent' => '',
                    'post_type' => "product",
                ];
                //Create Post
                $product_id = wp_insert_post($post, $wp_error);

                //set Product Category
                wp_set_object_terms($product_id, $product['product_cat'], 'product_cat');

                //set product type
                wp_set_object_terms($product_id, 'simple', 'product_type');

                update_post_meta($product_id, '_sku', $product['sku']);
                update_post_meta($product_id, 'total_sales', '0');

            //product found
            else:
                $post = [
                    'ID' => $product_id,
                    'post_title' => $product['title'],
                    'post_content' => $product['content'],
                ];
                $post_id = wp_update_post($post, true);
//              if (is_wp_error($post_id))
//              {
//                  $errors = $post_id->get_error_messages();
//                  foreach ($errors as $error)
//                  {
//                      echo $error;
//                  }
//              }
            endif;

            update_post_meta($product_id, '_visibility', 'visible');
            update_post_meta($product_id, '_stock_status', 'instock');
            update_post_meta($product_id, '_product_attributes', array());
            update_post_meta($product_id, '_manage_stock', "yes");
            update_post_meta($product_id, '_backorders', "no");
            update_post_meta($product_id, '_stock', $product['qty']);
            update_post_meta($product_id, '_price', $product['price']);
            //update_post_meta($product_id, '_downloadable', 'yes');
            //update_post_meta($product_id, '_virtual', 'yes');
            //update_post_meta($product_id, '_regular_price', "1");
            //update_post_meta($product_id, '_sale_price', "1");
            //update_post_meta($product_id, '_purchase_note', "");
            //update_post_meta($product_id, '_featured', "no");
            //update_post_meta($product_id, '_weight', "");
            //update_post_meta($product_id, '_length', "");
            //update_post_meta($product_id, '_width', "");
            //update_post_meta($product_id, '_height', "");
            //update_post_meta($product_id, '_sale_price_dates_from', "");
            //update_post_meta($product_id, '_sale_price_dates_to', "");
            //update_post_meta($product_id, '_price', "1");
            //update_post_meta($product_id, '_sold_individually', "");
        endforeach;
    endif;
}

这将让您简要了解如何创建/更新产品;如果您需要任何进一步的帮助,那么您必须分享您的 4-5 个数组元素,以便我可以了解您想要创建什么类型的产品以及它将具有什么字段/元。

希望这有帮助!


1
投票

适用于 WooCommerce 3.0 或更高版本。

假设您有一个像这样的数组,并且您有 Unique

SKU
来识别产品。

$products = [
    0 => [
        'title' => 'My Simple product 1',
        'sku' => 'sku1',
        'category_ids' => [23,45]
    //...
    //...
    ],
    1 => [
        'title' => 'My Simple product 1',
        'sku' => 'sku1'
    //...
    //...
    ]
];

通过

wh_myCustomProduct()
方法传递上面的数组。

function wh_myCustomProduct($product_array)
{
    if (!empty($product_array)):
        foreach ($product_array as $product):
            $product_id = wc_get_product_id_by_sku($product['sku']);
            //no product exist with the given SKU so create one
            if (empty($product_id)):
                
                $product_id = wh_createOrUpdateProduct($product);
            //product found
            else:
                
                $product_id = wh_createOrUpdateProduct($product,$product_id);
            endif;

        endforeach;
    endif;
}

function wh_createOrUpdateProduct($product, $productId = 0){
    $objProduct = new WC_Product($productId);
    $objProduct->set_sku($product['id']); //Set product SKU.
    $objProduct->set_name($product['title']); //Set product name.
    $objProduct->set_description($product['description']); //Set product description.
    $objProduct->set_description($product['price']); //Set product price.


    $objProduct->set_category_ids($product['category_ids']); //Set product category ID.

    $objProduct->set_stock_status('instock');
    $objProduct->set_manage_stock(true); //Set true if you want WooCommerce to manage your stock
    $objProduct->set_stock_quantity($product['rating']['count']); //Set product stock qty.
    $objProduct->set_status('publish'); //Set product status

    $productID = $objProduct->save(); //Saving the data to create new product, it will return product ID.
    return $productID;
}

希望这有帮助!

参考:

相关:


0
投票
how to import bulk of products in woocommerce using csv

add_action('wp_ajax_import_csv', 'import_csv');
function import_csv()
{
    if (!isset($_FILES['csv_file'])) {
        wp_send_json_error(['message' => 'No file uploaded.']);
        wp_die();
    }

    $csv_file = $_FILES['csv_file']['tmp_name'];

    if (($handle = fopen($csv_file, 'r')) === false) {
        wp_send_json_error(['message' => 'Could not open CSV file.']);
        wp_die();
    }

    $headers = fgetcsv($handle);
    if (!$headers) {
        fclose($handle);
        wp_send_json_error(['message' => 'Invalid CSV file.']);
        wp_die();
    }

    $products_updated = 0;
    $products_created = 0;
    while (($data = fgetcsv($handle)) !== false) {
        //$data = array_combine($headers, $row);
        $sku = $data[11];
        global $wpdb;
        $product_id = $wpdb->get_var($wpdb->prepare("
            SELECT p.ID 
            FROM {$wpdb->posts} AS p
            INNER JOIN {$wpdb->postmeta} AS pm 
            ON p.ID = pm.post_id
            WHERE p.post_type = 'product' 
            AND pm.meta_key = '_sku' 
            AND pm.meta_value = %s
        ", $sku));


        if ($product_id) {
            $product = wc_get_product($product_id);
            $products_updated++;
        } else {

            $product = new WC_Product_Variable();
            $products_created++;
        }

        $product->set_name($data[0]);
        $product->set_description($data[1]);
        $product->set_price($data[2]);
        $product->set_regular_price($data[2]);
        $product->set_height($data[3]);
        $product->set_width($data[4]);
        $product->set_length($data[5]);
        $product->set_weight($data[6]);
        $product->set_status('publish');
        $product->set_stock_quantity(10);
        $product->set_manage_stock(true);
        $product->set_sku($data[11]);

        $upload_dir = wp_upload_dir();
        $galleryImages = [];

        for ($i = 7; $i <= 10; $i++) {

            if (!empty($data[$i])) {

                $featured_image_path = $upload_dir['path'] . '/' . $data[$i];
                $image_extension = pathinfo($data[$i], PATHINFO_EXTENSION);
                $image_type = 'image/' . $image_extension;

                $attachment =   array(
                    'post_mime_type' => $image_type,
                    'post_title'     =>  $data[$i],
                    'post_status'    => 'inherit',
                    'guid'           => $upload_dir['url'] . '/' . $data[$i]
                );

                $attachment_id = wp_insert_attachment($attachment, $featured_image_path);
                $attachment_data = wp_generate_attachment_metadata($attachment_id, $featured_image_path);
                wp_update_attachment_metadata($attachment_id, $attachment_data);

                if ($i == 7) {
                    $product->set_image_id($attachment_id);
                } else {
                    $galleryImages[] = $attachment_id;
                }
            }
        }

        if (!empty($galleryImages)) {
            $product->set_gallery_image_ids($galleryImages);
        }

        $product_id = $product->save();
    }

    fclose($handle);

    wp_send_json_success([
        'message' => "$products_created products were created, and $products_updated products were updated successfully."
    ]);
}

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