php WooCommerce:通过代码创建产品

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11503646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:40:40  来源:igfitidea点击:

WooCommerce: Create product by code

phpwordpresswoocommerce

提问by Beer Brother

My store sells vinyl stickers. Each product (sticker) has a 144 variations (24 colors, 3 sizes and 2 orientation). Each variation is necessary to assign a unique SKU.

我的商店出售乙烯基贴纸。每个产品(贴纸)有 144 种变化(24 种颜色、3 种尺寸和 2 种方向)。每个变体都是分配唯一 SKU 所必需的。

Manually populate catalog is unrealistic. I am going to make a form in which the user specifies the name, description, and the main image of the product, as well as the possible sizes and colors. When processing the form i need to create a product and all of its variations.

手动填充目录是不现实的。我将制作一个表格,用户可以在其中指定产品的名称、描述和主要图像,以及可能的尺寸和颜色。在处理表单时,我需要创建一个产品及其所有变体。

How to create a product and its variations?

如何创建产品及其变体?

回答by Avant Garde

I had a similar situation, here's what I found out.

我有类似的情况,这是我发现的。

Products are actually a custom post type(quite obvious! :P), so you can use wp_insert_postto insert a new product. After you insert, you get the id of the new product post type, use update_post_metato set a meta key and meta value as _visibilityand visiblerespectively. If you don't set the visibility, your newly added product will never be visible in your shop. Alternatively you can set the visibility from the back end as well. For the various sizes of the product, use variations on that product. You can set a different type, price, SKU etc. for each variation. All these are post meta, hence you can use php code to add the variations and stuff. Study the postmetatable to see the key names.

产品实际上是一种自定义帖子类型(很明显!:P),因此您可以使用它wp_insert_post来插入新产品。插入之后,你得到新的产品类型后的ID,使用update_post_meta设置Meta键和元值_visibilityvisible分别。如果您不设置可见性,您新添加的产品将永远不会在您的商店中可见。或者,您也可以从后端设置可见性。对于不同尺寸的产品,请使用该产品的变体。您可以为每个变体设置不同的类型、价格、SKU 等。所有这些都是后期元数据,因此您可以使用 php 代码来添加变体和内容。研究postmeta表格以查看键名。

回答by Vedran ?ego

As Jason wrote in his comment, REST API is the way to go here. This can be done even without HTTP REST requests, making it work even on Wordpress installations that have their REST interface disabled.

正如 Jason 在他的评论中所写的那样,REST API 是通往这里的方式。即使没有 HTTP REST 请求,这也可以完成,即使在禁用了 REST 接口的 Wordpress 安装上也能正常工作。

Here is a simple function that I made for this purpose:

这是我为此目的制作的一个简单函数:

$products_controler = new WC_REST_Products_Controller();
function create_item($rest_request) {
    global $products_controler;
    if (!isset($rest_request['status']))
        $rest_request['status'] = 'publish';
    $wp_rest_request = new WP_REST_Request('POST');
    $wp_rest_request->set_body_params($rest_request);
    return $products_controler->create_item($wp_rest_request);
}

Here, $rest_requestis an array that you'd usually send via REST (see the docs here).

$rest_request是一个您通常通过 REST 发送的数组(请参阅此处的文档)。

The $products_controlervariable is global because I needed to call this function multiple times and I didn't want to recreate the object each time. Feel free to make it local.

这个$products_controler变量是全局的,因为我需要多次调用这个函数,而且我不想每次都重新创建对象。随意将其设为本地。

This works for all types of products (simple, grouped, variable,...) and it should be more resistant to internal changes of WooCommerce than adding the products manually through wp_insert_postand update_post_meta.

这适用于所有类型的产品(简单的、分组的、可变的……),并且它应该比通过wp_insert_post和手动添加产品更能抵抗 WooCommerce 的内部更改update_post_meta

Edit:Given that this answer still get an occasional upvote, here is a WooCommerce 3.0+update. The change is that the variations no longer get added automatically, so we have to do it by ourselves.

编辑:鉴于这个答案仍然偶尔会得到赞成,这里是WooCommerce 3.0+更新。变化是不再自动添加变化,所以我们必须自己做。

This is the current version of the function:

这是该函数的当前版本:

protected function create_item( $rest_request ) {
    if ( ! isset( $rest_request['status'] ) ) {
        $rest_request['status'] = $this->plugin->get_option( 'default_published_status' );
    }
    if ( ! isset( $this->products_controler ) ) {
        $this->products_controler = new WC_REST_Products_Controller();
    }
    $wp_rest_request = new WP_REST_Request( 'POST' );
    $wp_rest_request->set_body_params( $rest_request );
    $res = $this->products_controler->create_item( $wp_rest_request );
    $res = $res->data;
    // The created product must have variations
    // If it doesn't, it's the new WC3+ API which forces us to build those manually
    if ( ! isset( $res['variations'] ) )
        $res['variations'] = array();
    if ( count( $res['variations'] ) == 0 && count( $rest_request['variations'] ) > 0 ) {
        if ( ! isset( $this->variations_controler ) ) {
            $this->variations_controler = new WC_REST_Product_Variations_Controller();
        }
        foreach ( $rest_request['variations'] as $variation ) {
            $wp_rest_request = new WP_REST_Request( 'POST' );
            $variation_rest = array(
                'product_id' => $res['id'],
                'regular_price' => $variation['regular_price'],
                'image' => array( 'id' => $variation['image'][0]['id'], ),
                'attributes' => $variation['attributes'],
            );
            $wp_rest_request->set_body_params( $variation_rest );
            $new_variation = $this->variations_controler->create_item( $wp_rest_request );
            $res['variations'][] = $new_variation->data;
        }
    }
    return $res;
}

This is used in Kite Print and Dropshipping on Demandplugin, starting from the (soon to be published) version 1.1, in file api/publish_products.php.

这用于Kite Print 和 Dropshipping on Demand插件,从(即将发布)版本 1.1 开始,在文件api/publish_products.php.

There is also a much longer "fast" version called create_products_fastwhich writes directly to the database, making it potentially less resilient to future WP/WC changes, but it is much faster (few seconds vs. few minutes for our 34 products range on my test computer).

还有一个更长的“快速”版本称为create_products_fast直接写入数据库,使其对未来 WP/WC 更改的弹性可能降低,但速度要快得多(在我的测试中,我们的 34 种产品系列为几秒与几分钟计算机)。

回答by Sophivorus

Based on Vedran's answer, here's the minimal code for posting a WooCommerce product via PHP:

根据Vedran 的回答,这是通过 PHP 发布 WooCommerce 产品的最小代码:

$data = [
    'name' => 'Test product',
    'description' => 'Lorem ipsum',
];
$request = new WP_REST_Request( 'POST' );
$request->set_body_params( $data );
$products_controller = new WC_REST_Products_Controller;
$response = $products_controller->create_item( $request );

回答by herr

Please refer to woocommerce-with-php-code, where the full code is given.

请参阅woocommerce-with-php-code,其中给出了完整代码。

As Avant Garde said, products are added in post with:

正如前卫所说,产品在后期添加:

post_type = "product"

post_type = "product"

回答by vijay

i use this code:

我使用这个代码:

$sku = 21333;
$size = 'S';
$stock = 2;
$price_a = 60;
$price_b = 30;

$product_parent = get_product_by_sku($sku);
$product = new WC_Product_Variable($product_parent->id);
$variations = $product->get_available_variations();

// First off all delete all variations
foreach($variations as $prod_variation) {
  $metaid=mysql_query("SELECT meta_id FROM wp_postmeta WHERE post_id = ".$prod_variation['variation_id']);
  while ($row = mysql_fetch_assoc($metaid)) {
    mysql_query("DELETE FROM wp_postmeta WHERE meta_id = ".$row['meta_id']);
  }
  mysql_query("DELETE FROM wp_posts WHERE ID = ".$prod_variation['variation_id']);
}

// Now add new variation
$thevariation = array(
  'post_title'=> '',
  'post_name' => 'product-' . $product_parent->id . '-variation',
  'post_status' => 'publish',
  'post_parent' => $product_parent->id,
  'post_type' => 'product_variation',
  'guid'=>home_url() . '/?product_variation=product-' . $product_parent->id . '-variation'
);
$variation_id = wp_insert_post( $thevariation );
update_post_meta($variation_id, 'post_title', 'Variation #' . $variation_id . ' of '. $product_parent->id);

wp_set_object_terms( $variation_id, $size, 'pa_size' );
update_post_meta($variation_id, 'attribute_pa_size', $size);

update_post_meta($variation_id, '_regular_price', $price_a);
update_post_meta($variation_id, '_downloadable_files', '');
update_post_meta($variation_id, '_download_expiry', '');
update_post_meta($variation_id, '_download_limit', '');
update_post_meta($variation_id, '_sale_price_dates_to', '');
update_post_meta($variation_id, '_sale_price_dates_from', '');
update_post_meta($variation_id, '_backorders', 'no');
update_post_meta($variation_id, '_stock_status', 'instock');
update_post_meta($variation_id, '_height', '');
update_post_meta($variation_id, '_manage_stock', 'yes');
update_post_meta($variation_id, '_width', '');
update_post_meta($variation_id, '_sale_price_dates_from', '');
update_post_meta($variation_id, '_backorders', 'no');
update_post_meta($variation_id, '_stock_status', 'instock');
update_post_meta($variation_id, '_manage_stock', 'yes');
update_post_meta($variation_id, '_height', '');
update_post_meta($variation_id, '_width', '');
update_post_meta($variation_id, '_length', '');
update_post_meta($variation_id, '_weight', '');
update_post_meta($variation_id, '_downloadable', 'no');
update_post_meta($variation_id, '_virtual', 'no');
update_post_meta($variation_id, '_thumbnail_id', '0');
update_post_meta($variation_id, '_sku', '');

update_post_meta($variation_id, '_sale_price', $price_b);
update_post_meta($variation_id, '_price', $price_b);
update_post_meta($product_parent->id, '_min_variation_price', $price_b);
update_post_meta($product_parent->id, '_max_variation_price', $price_b);
update_post_meta($product_parent->id, '_min_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_max_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_min_variation_regular_price', $price_a);
update_post_meta($product_parent->id, '_max_variation_regular_price', $price_a);
update_post_meta($product_parent->id, '_min_regular_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_max_regular_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_min_variation_sale_price', $price_b);
update_post_meta($product_parent->id, '_max_variation_sale_price', $price_b);
update_post_meta($product_parent->id, '_min_sale_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_max_sale_price_variation_id', $variation_id);
update_post_meta($product_parent->id, '_price', $price_b);

update_post_meta( $variation_id, '_stock', $stock );
update_post_meta($product_parent->id, 'post_status', 'publish');