使用 Woocommerce 3 中的 CRUD 方法以编程方式创建产品 [英] Create programmatically a product using CRUD methods in Woocommerce 3

查看:31
本文介绍了使用 Woocommerce 3 中的 CRUD 方法以编程方式创建产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 PHP 代码以编程方式创建一个新的 Woocommerce 产品,并且我已经尝试使用 Woocommerce 3 CRUD 方法:

//Woocommerce CRUD$objProduct = new WC_Product_Simple();$objProduct->set_name('我的产品 1');//设置产品名称.$objProduct->set_status('publish');//设置产品状态.//$objProduct->set_featured(FALSE);//设置产品是否有特色.|布尔值$objProduct->set_catalog_visibility('visible');//设置目录可见性.|字符串 $visibility 选项:隐藏"、可见"、搜索"和目录".$objProduct->set_description('我的自定义长描述');//设置产品描述.//$objProduct->set_short_description('我的简短描述');//设置产品简短描述.//$objProduct->set_sku('U-123');//设置SKU$objProduct->set_price(5.00);//设置产品的有效价格.//$objProduct->set_regular_price(5.00);//设置产品的正常价格.//$objProduct->set_sale_price();//设置产品的销售价格.//$objProduct->set_date_on_sale_from();//设置销售日期.|字符串|整数|null $date UTC 时间戳,或 ISO 8601 日期时间.如果 DateTime 字符串没有时区或偏移量,则将采用 WordPress 站点时区.如果没有日期,则为 Null.//$objProduct->set_date_on_sale_to();//设置销售日期到.|字符串|整数|null $date UTC 时间戳,或 ISO 8601 日期时间.如果 DateTime 字符串没有时区或偏移量,则将采用 WordPress 站点时区.如果没有日期,则为 Null.//$objProduct->set_manage_stock(TRUE);//设置产品是否管理库存.|布尔值//$objProduct->set_stock_quantity(10);//设置可供出售的物品数量.//$objProduct->set_stock_status('instock');//设置库存状态.|字符串 $status 'instock'、'outofstock' 和 'onbackorder'//$objProduct->set_backorders('no');//设置缺货.|字符串 $backorders 选项:是"、否"或通知".//$objProduct->set_sold_individually(FALSE);//设置是否应该单独出售.|布尔值//$objProduct->set_weight();//设置产品的重量.//$objProduct->set_length();//设置产品长度.//$objProduct->set_width();//设置产品宽度.//$objProduct->set_height();//设置产品高度.//$objProduct->set_upsell_ids($upsell_ids);//设置追加销售ID.|来自追加销售产品的数组 $upsell_ids ID.//$objProduct->set_cross_sell_ids($cross_sell_ids);//设置交叉销售ID.|来自交叉销售产品的数组 $cross_sell_ids ID.$objProduct->set_reviews_allowed(TRUE);//设置是否允许评论.|布尔值//$objProduct->set_purchase_note($purchase_note);//设置购买备注.|字符串 $purchase_note 购买笔记.$attribute = new WC_Product_Attribute();$attribute->set_id(wc_attribute_taxonomy_id_by_name('pa_color'));//如果传递属性名来获取ID$attribute->set_name('pa_color');//属性名$attribute->set_options('red');//属性值$attribute->set_position(1);//属性显示顺序$attribute->set_visible(1);//属性可见性$attribute->set_variation(0);//是否将此属性用作varint$raw_attributes[] = $attribute;//<--- 将属性存储在数组中$attribute = new WC_Product_Attribute();$attribute->set_id(25);$attribute->set_name('pa_size');$attribute->set_options('XL');$attribute->set_position(2);$attribute->set_visible(1);$attribute->set_variation(0);$raw_attributes[] = $attribute;//<--- 将属性存储在数组中$objProduct->set_attributes($raw_attributes);//设置产品属性.|数组 $raw_attributes WC_Product_Attribute 对象数组.//$objProduct->set_category_ids($term_ids);//设置产品类别.|数组 $term_ids 术语 ID 列表.//$objProduct->set_tag_ids($term_ids);//设置产品标签.|数组 $term_ids 术语 ID 列表.//$objProduct->set_image_id();//设置主图片ID.|int|string $image_id 产品图片 ID.//$objProduct->set_gallery_image_ids();//设置画廊附件ID.|数组 $image_ids 图像 ID 列表.$new_product_id = $objProduct->save();//保存数据以创建新产品,它将返回产品ID.返回;}

但我收到此错误:

<块引用>

2018 年 10 月 22 日 20:25:19 UTC] PHP 致命错误:未捕获的错误: 在/home/u1771p590/domains/famyfuerza.com/public_html/store 中找不到WC_Product_Simple"类/wp-content/plugins/ff-dropship-data-scraper/ff-dropship-data-scraper.php:165堆栈跟踪:
- #0/home/u1771p590/domains/famyfuerza.com/public_html/store/wp-content/plugins/ff-dropship-data-scraper/ff-dropship-data-scraper.php(233): curl_download('https://www.ban...')
- #1/home/u1771p590/domains/famyfuerza.com/public_html/store/wp-settings.php(305): include_once('/home/u1771p590...')
- #2/home/u1771p590/domains/famyfuerza.com/public_html/store/wp-config.php(112): require_once('/home/u1771p590...')
- #3/home/u1771p590/domains/famyfuerza.com/public_html/store/wp-load.php(37): require_once('/home/u1771p590...')
- #4/home/u1771p590/domains/famyfuerza.com/public_html/store/wp-admin/admin.php(31): require_once('/home/u1771p590...')
- #5/home/u1771p590/domains/famyfuerza.com/public_html/store/wp-admin/index.php(10): require_once('/home/u1771p590...')
- #6 {main}
在第 165 行的/home/u1771p590/domains/famyfuerza.com/public_html/store/wp-content/plugins/ff-dropship-data-scraper/ff-dropship-data-scraper.php 中抛出

我曾尝试包含简单的产品类,但这产生了另一个错误,表明缺少另一个类.

有人知道如何解决这个问题吗?或者有另一种通过代码创建woocommerce产品的方法?

解决方案

您没有从您的自定义 Dropship Data Scraper 插件.

有罪的可能主要是两件事:

  1. 您尚未安装 Woocommerce.
  2. 插件 Dropship Data Scraper 已过时,需要更改以处理 woocommerce.

<块引用>

尝试在您的插件中包含全局 Woocommerce 对象并启用 Woocommerce 支持.


使用 Woocommerce 3 中引入的 CRUD 方法以编程方式创建产品 这是使其工作的正确方法.

<块引用>

如果您需要处理产品属性创建产品变体创建,请参考:

<块引用>

所有产品属性及其术语值需要在创建之前.产品类别和产品标签也是如此.

1) 代码功能:

//用于产品创建的自定义函数(仅适用于 Woocommerce 3+)函数 create_product( $args ){if(!function_exists('wc_get_product_object_type') && !function_exists('wc_prepare_product_attributes'))返回假;//获取产品对象的空实例(定义它的类型)$product = wc_get_product_object_type( $args['type'] );如果(!$产品)返回假;//产品名称 (Title) 和 slug$product->set_name( $args['name'] );//名称(标题).if( isset( $args['slug'] ) )$product->set_name( $args['slug'] );//描述和简短描述:$product->set_description( $args['description'] );$product->set_short_description( $args['short_description'] );//状态('publish'、'pending'、'draft' 或 'trash')$product->set_status( isset($args['status']) ? $args['status'] : 'publish' );//可见性(隐藏"、可见"、搜索"或目录")$product->set_catalog_visibility( isset($args['visibility']) ? $args['visibility'] : 'visible');//精选(布尔值)$product->set_featured( isset($args['featured']) ? $args['featured'] : false );//虚拟(布尔)$product->set_virtual( isset($args['virtual']) ? $args['virtual'] : false );//价格$product->set_regular_price( $args['regular_price'] );$product->set_sale_price( isset( $args['sale_price'] ) ? $args['sale_price'] : '' );$product->set_price( isset( $args['sale_price'] ) ? $args['sale_price'] : $args['regular_price'] );if( isset( $args['sale_price'] ) ){$product->set_date_on_sale_from( isset( $args['sale_from'] ) ? $args['sale_from'] : '' );$product->set_date_on_sale_to( isset( $args['sale_to'] ) ? $args['sale_to'] : '' );}//可下载(布尔值)$product->set_downloadable( isset($args['downloadable']) ? $args['downloadable'] : false );if( isset($args['downloadable']) && $args['downloadable'] ) {$product->set_downloads( isset($args['downloads']) ? $args['downloads'] : array() );$product->set_download_limit( isset($args['download_limit']) ? $args['download_limit'] : '-1' );$product->set_download_expiry( isset($args['download_expiry']) ? $args['download_expiry'] : '-1' );}//税收if ( get_option( 'woocommerce_calc_taxes' ) === 'yes' ) {$product->set_tax_status( isset($args['tax_status']) ? $args['tax_status'] : 'taxable');$product->set_tax_class( isset($args['tax_class']) ? $args['tax_class'] : '' );}//SKU 和 Stock(不是虚拟产品)if( isset($args['virtual']) && ! $args['virtual'] ) {$product->set_sku( isset( $args['sku'] ) ? $args['sku'] : '' );$product->set_manage_stock( isset( $args['manage_stock'] ) ? $args['manage_stock'] : false );$product->set_stock_status( isset( $args['stock_status'] ) ? $args['stock_status'] : 'instock' );if( isset( $args['manage_stock'] ) && $args['manage_stock'] ) {$product->set_stock_status( $args['stock_qty'] );$product->set_backorders( isset( $args['backorders'] ) ? $args['backorders'] : 'no' );//是"、否"或通知"}}//单独出售$product->set_sold_individually( isset( $args['sold_individually'] ) ? $args['sold_individually'] : false );//重量、尺寸和运输等级$product->set_weight( isset( $args['weight'] ) ? $args['weight'] : '' );$product->set_length( isset( $args['length'] ) ? $args['length'] : '' );$product->set_width( isset( $args['width'] ) ? $args['width'] : '' );$product->set_height( isset( $args['height'] ) ? $args['height'] : '' );if( isset( $args['shipping_class_id'] ) )$product->set_shipping_class_id( $args['shipping_class_id'] );//追加销售和交叉销售(ID)$product->set_upsell_ids( isset( $args['upsells'] ) ? $args['upsells'] : '' );$product->set_cross_sell_ids( isset( $args['cross_sells'] ) ? $args['upsells'] : '' );//属性和默认属性if( isset( $args['attributes'] ) )$product->set_attributes(wc_prepare_product_attributes($args['attributes']));if( isset( $args['default_attributes'] ) )$product->set_default_attributes( $args['default_attributes'] );//需要特殊的格式//评论、购买说明和菜单顺序$product->set_reviews_allowed( isset( $args['reviews'] ) ? $args['reviews'] : false );$product->set_purchase_note( isset( $args['note'] ) ? $args['note'] : '' );if( isset( $args['menu_order'] ) )$product->set_menu_order( $args['menu_order'] );//产品类别和标签if( isset( $args['category_ids'] ) )$product->set_category_ids( $args['category_ids'] );if( isset( $args['tag_ids'] ) )$product->set_tag_ids( $args['tag_ids'] );//图片和图库$product->set_image_id( isset( $args['image_id'] ) ? $args['image_id'] : "");$product->set_gallery_image_ids( isset( $args['gallery_ids'] ) ? $args['gallery_ids'] : array() );## --- 保存产品 --- ##$product_id = $product->save();返回 $product_id;}//返回正确产品对象实例的实用函数函数 wc_get_product_object_type( $type ) {//获取 WC_Product 对象的实例(取决于他的类型)if( isset($args['type']) && $args['type'] === '变量' ){$product = new WC_Product_Variable();} elseif( isset($args['type']) && $args['type'] === 'grouped' ){$product = new WC_Product_Grouped();} elseif( isset($args['type']) && $args['type'] === 'external' ){$product = new WC_Product_External();} 别的 {$product = new WC_Product_Simple();//简单"默认情况下}if( !is_a( $product, 'WC_Product' ) )返回假;别的返回 $product;}//保存前准备产品属性的实用函数函数 wc_prepare_product_attributes( $attributes ){全球 $woocommerce;$data = 数组();$位置 = 0;foreach( $attributes as $taxonomy => $values ){if(!taxonomy_exists($taxonomy))继续;//获取 WC_Product_Attribute 对象的实例$attribute = new WC_Product_Attribute();$term_ids = array();//遍历术语名称foreach( $values['term_names'] 作为 $term_name ){if( term_exists( $term_name, $taxonomy ) )//从词条名称获取并设置数组中的词条ID$term_ids[] = get_term_by('name', $term_name, $taxonomy )->term_id;别的继续;}$taxonomy_id = wc_attribute_taxonomy_id_by_name( $taxonomy );//获取分类ID$attribute->set_id( $taxonomy_id );$attribute->set_name( $taxonomy );$attribute->set_options( $term_ids );$attribute->set_position( $position );$attribute->set_visible( $values['is_visible'] );$attribute->set_variation( $values['for_variation'] );$data[$taxonomy] = $attribute;//设置在一个数组中$位置++;//增加位置}返回 $data;}

2) 用法: - 具有 2 个产品属性颜色"的简单产品创建示例和尺寸":

$product_id = create_product( 数组('类型' =>'',//默认为简单乘积'名称' =>__(产品名称",woocommerce"),'说明' =>__(产品描述……",woocommerce"),'short_description' =>__(产品简短描述……",woocommerce"),//'sku' =>'','regular_price' =>'5.00',//产品价格//'sale_price' =>'','reviews_allowed' =>真的,'属性' =>大批(//分类法和术语名称值'pa_color' =>大批('term_names' =>数组('红色','蓝色'),'is_visible' =>真的,'for_variation' =>错误的,),'pa_size' =>大批('term_names' =>数组('X 大'),'is_visible' =>真的,'for_variation' =>错误的,),),) );//显示创建的产品ID回声 $product_id;

仅使用 Woocommerce 3 CRUD 方法进行测试和工作.

I'd like to create a new Woocommerce product programmatically with PHP code and I have tried it with the Woocommerce 3 CRUD methods:

//Woocommerce CRUD
$objProduct = new WC_Product_Simple();

$objProduct->set_name('My Product 1'); //Set product name.
$objProduct->set_status('publish'); //Set product status.
//$objProduct->set_featured(FALSE); //Set if the product is featured.                          | bool
$objProduct->set_catalog_visibility('visible'); //Set catalog visibility.                   | string $visibility Options: 'hidden', 'visible', 'search' and 'catalog'.
$objProduct->set_description('My custom long description'); //Set product description.
//$objProduct->set_short_description('My short description'); //Set product short description.
//$objProduct->set_sku('U-123'); //Set SKU

$objProduct->set_price(5.00); //Set the product's active price.
//$objProduct->set_regular_price(5.00); //Set the product's regular price.
//$objProduct->set_sale_price(); //Set the product's sale price.
//$objProduct->set_date_on_sale_from(); //Set date on sale from.                              | string|integer|null $date UTC timestamp, or ISO 8601 DateTime. If the DateTime string has no timezone or offset, WordPress site timezone will be assumed. Null if their is no date.
//$objProduct->set_date_on_sale_to();//Set date on sale to.                                   | string|integer|null $date UTC timestamp, or ISO 8601 DateTime. If the DateTime string has no timezone or offset, WordPress site timezone will be assumed. Null if their is no date.

//$objProduct->set_manage_stock(TRUE); //Set if product manage stock.                         | bool
//$objProduct->set_stock_quantity(10); //Set number of items available for sale.
//$objProduct->set_stock_status('instock'); //Set stock status.                               | string $status 'instock', 'outofstock' and 'onbackorder'
//$objProduct->set_backorders('no'); //Set backorders.                                        | string $backorders Options: 'yes', 'no' or 'notify'.
//$objProduct->set_sold_individually(FALSE); //Set if should be sold individually.            | bool

//$objProduct->set_weight(); //Set the product's weight.
//$objProduct->set_length(); //Set the product length.
//$objProduct->set_width(); //Set the product width.
//$objProduct->set_height(); //Set the product height.

//$objProduct->set_upsell_ids($upsell_ids); //Set upsell IDs.                               | array $upsell_ids IDs from the up-sell products.
//$objProduct->set_cross_sell_ids($cross_sell_ids); //Set crosssell IDs.                    | array $cross_sell_ids IDs from the cross-sell products.

$objProduct->set_reviews_allowed(TRUE); //Set if reviews is allowed.                        | bool

//$objProduct->set_purchase_note($purchase_note); //Set purchase note.                      | string $purchase_note Purchase note.


$attribute = new WC_Product_Attribute();
$attribute->set_id(wc_attribute_taxonomy_id_by_name('pa_color')); //if passing the attribute name to get the ID
$attribute->set_name('pa_color'); //attribute name
$attribute->set_options('red'); // attribute value
$attribute->set_position(1); //attribute display order
$attribute->set_visible(1); //attribute visiblity
$attribute->set_variation(0);//to use this attribute as varint or not

$raw_attributes[] = $attribute; //<--- storing the attribute in an array

$attribute = new WC_Product_Attribute();
$attribute->set_id(25);
$attribute->set_name('pa_size');
$attribute->set_options('XL');
$attribute->set_position(2);
$attribute->set_visible(1);
$attribute->set_variation(0);

$raw_attributes[] = $attribute; //<--- storing the attribute in an array

$objProduct->set_attributes($raw_attributes); //Set product attributes.                   | array $raw_attributes Array of WC_Product_Attribute objects.

//$objProduct->set_category_ids($term_ids); //Set the product categories.                   | array $term_ids List of terms IDs.
//$objProduct->set_tag_ids($term_ids); //Set the product tags.                              | array $term_ids List of terms IDs.

//$objProduct->set_image_id(); //Set main image ID.                                         | int|string $image_id Product image id.
//$objProduct->set_gallery_image_ids(); //Set gallery attachment ids.                       | array $image_ids List of image ids.

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

return;
}

But I get this error:

22-Oct-2018 20:25:19 UTC] PHP Fatal error: Uncaught Error: Class 'WC_Product_Simple' not found in /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-content/plugins/ff-dropship-data-scraper/ff-dropship-data-scraper.php:165 Stack trace:
- #0 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-content/plugins/ff-dropship-data-scraper/ff-dropship-data-scraper.php(233): curl_download('https://www.ban...')
- #1 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-settings.php(305): include_once('/home/u1771p590...')
- #2 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-config.php(112): require_once('/home/u1771p590...')
- #3 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-load.php(37): require_once('/home/u1771p590...')
- #4 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-admin/admin.php(31): require_once('/home/u1771p590...')
- #5 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-admin/index.php(10): require_once('/home/u1771p590...')
- #6 {main}
thrown in /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-content/plugins/ff-dropship-data-scraper/ff-dropship-data-scraper.php on line 165

I have tried to include the simple product class, but that produced another error which said that another class was missing.

Does somebody know how to fix this? Or has another method to create a woocommerce product via code?

解决方案

You are not accessing the WC_Product_simple instance object from your custom Dropship Data Scraper plugin.

The guilty can be mostly 2 things:

  1. You have not installed Woocommerce.
  2. The plugin Dropship Data Scraper is outdated and needs changes, to handle woocommerce.

Try to include the global Woocommerce object and to enable Woocommerce support in your plugin.


To create a product programmatically using CRUD methods introduced in Woocommerce 3 here is the correct way to make it work.

If you need to handle product attributes creation or product variations creation, refer to:

All product attributes and their term values need to be created before. Same thing for product categories and product tags.

1) The code functions:

// Custom function for product creation (For Woocommerce 3+ only)
function create_product( $args ){

    if( ! function_exists('wc_get_product_object_type') && ! function_exists('wc_prepare_product_attributes') )
        return false;

    // Get an empty instance of the product object (defining it's type)
    $product = wc_get_product_object_type( $args['type'] );
    if( ! $product )
        return false;

    // Product name (Title) and slug
    $product->set_name( $args['name'] ); // Name (title).
    if( isset( $args['slug'] ) )
        $product->set_name( $args['slug'] );

    // Description and short description:
    $product->set_description( $args['description'] );
    $product->set_short_description( $args['short_description'] );

    // Status ('publish', 'pending', 'draft' or 'trash')
    $product->set_status( isset($args['status']) ? $args['status'] : 'publish' );

    // Visibility ('hidden', 'visible', 'search' or 'catalog')
    $product->set_catalog_visibility( isset($args['visibility']) ? $args['visibility'] : 'visible' );

    // Featured (boolean)
    $product->set_featured(  isset($args['featured']) ? $args['featured'] : false );

    // Virtual (boolean)
    $product->set_virtual( isset($args['virtual']) ? $args['virtual'] : false );

    // Prices
    $product->set_regular_price( $args['regular_price'] );
    $product->set_sale_price( isset( $args['sale_price'] ) ? $args['sale_price'] : '' );
    $product->set_price( isset( $args['sale_price'] ) ? $args['sale_price'] :  $args['regular_price'] );
    if( isset( $args['sale_price'] ) ){
        $product->set_date_on_sale_from( isset( $args['sale_from'] ) ? $args['sale_from'] : '' );
        $product->set_date_on_sale_to( isset( $args['sale_to'] ) ? $args['sale_to'] : '' );
    }

    // Downloadable (boolean)
    $product->set_downloadable(  isset($args['downloadable']) ? $args['downloadable'] : false );
    if( isset($args['downloadable']) && $args['downloadable'] ) {
        $product->set_downloads(  isset($args['downloads']) ? $args['downloads'] : array() );
        $product->set_download_limit(  isset($args['download_limit']) ? $args['download_limit'] : '-1' );
        $product->set_download_expiry(  isset($args['download_expiry']) ? $args['download_expiry'] : '-1' );
    }

    // Taxes
    if ( get_option( 'woocommerce_calc_taxes' ) === 'yes' ) {
        $product->set_tax_status(  isset($args['tax_status']) ? $args['tax_status'] : 'taxable' );
        $product->set_tax_class(  isset($args['tax_class']) ? $args['tax_class'] : '' );
    }

    // SKU and Stock (Not a virtual product)
    if( isset($args['virtual']) && ! $args['virtual'] ) {
        $product->set_sku( isset( $args['sku'] ) ? $args['sku'] : '' );
        $product->set_manage_stock( isset( $args['manage_stock'] ) ? $args['manage_stock'] : false );
        $product->set_stock_status( isset( $args['stock_status'] ) ? $args['stock_status'] : 'instock' );
        if( isset( $args['manage_stock'] ) && $args['manage_stock'] ) {
            $product->set_stock_status( $args['stock_qty'] );
            $product->set_backorders( isset( $args['backorders'] ) ? $args['backorders'] : 'no' ); // 'yes', 'no' or 'notify'
        }
    }

    // Sold Individually
    $product->set_sold_individually( isset( $args['sold_individually'] ) ? $args['sold_individually'] : false );

    // Weight, dimensions and shipping class
    $product->set_weight( isset( $args['weight'] ) ? $args['weight'] : '' );
    $product->set_length( isset( $args['length'] ) ? $args['length'] : '' );
    $product->set_width( isset(  $args['width'] ) ?  $args['width']  : '' );
    $product->set_height( isset( $args['height'] ) ? $args['height'] : '' );
    if( isset( $args['shipping_class_id'] ) )
        $product->set_shipping_class_id( $args['shipping_class_id'] );

    // Upsell and Cross sell (IDs)
    $product->set_upsell_ids( isset( $args['upsells'] ) ? $args['upsells'] : '' );
    $product->set_cross_sell_ids( isset( $args['cross_sells'] ) ? $args['upsells'] : '' );

    // Attributes et default attributes
    if( isset( $args['attributes'] ) )
        $product->set_attributes( wc_prepare_product_attributes($args['attributes']) );
    if( isset( $args['default_attributes'] ) )
        $product->set_default_attributes( $args['default_attributes'] ); // Needs a special formatting

    // Reviews, purchase note and menu order
    $product->set_reviews_allowed( isset( $args['reviews'] ) ? $args['reviews'] : false );
    $product->set_purchase_note( isset( $args['note'] ) ? $args['note'] : '' );
    if( isset( $args['menu_order'] ) )
        $product->set_menu_order( $args['menu_order'] );

    // Product categories and Tags
    if( isset( $args['category_ids'] ) )
        $product->set_category_ids( $args['category_ids'] );
    if( isset( $args['tag_ids'] ) )
        $product->set_tag_ids( $args['tag_ids'] );


    // Images and Gallery
    $product->set_image_id( isset( $args['image_id'] ) ? $args['image_id'] : "" );
    $product->set_gallery_image_ids( isset( $args['gallery_ids'] ) ? $args['gallery_ids'] : array() );

    ## --- SAVE PRODUCT --- ##
    $product_id = $product->save();

    return $product_id;
}

// Utility function that returns the correct product object instance
function wc_get_product_object_type( $type ) {
    // Get an instance of the WC_Product object (depending on his type)
    if( isset($args['type']) && $args['type'] === 'variable' ){
        $product = new WC_Product_Variable();
    } elseif( isset($args['type']) && $args['type'] === 'grouped' ){
        $product = new WC_Product_Grouped();
    } elseif( isset($args['type']) && $args['type'] === 'external' ){
        $product = new WC_Product_External();
    } else {
        $product = new WC_Product_Simple(); // "simple" By default
    } 
    
    if( ! is_a( $product, 'WC_Product' ) )
        return false;
    else
        return $product;
}

// Utility function that prepare product attributes before saving
function wc_prepare_product_attributes( $attributes ){
    global $woocommerce;

    $data = array();
    $position = 0;

    foreach( $attributes as $taxonomy => $values ){
        if( ! taxonomy_exists( $taxonomy ) )
            continue;

        // Get an instance of the WC_Product_Attribute Object
        $attribute = new WC_Product_Attribute();

        $term_ids = array();

        // Loop through the term names
        foreach( $values['term_names'] as $term_name ){
            if( term_exists( $term_name, $taxonomy ) )
                // Get and set the term ID in the array from the term name
                $term_ids[] = get_term_by( 'name', $term_name, $taxonomy )->term_id;
            else
                continue;
        }

        $taxonomy_id = wc_attribute_taxonomy_id_by_name( $taxonomy ); // Get taxonomy ID

        $attribute->set_id( $taxonomy_id );
        $attribute->set_name( $taxonomy );
        $attribute->set_options( $term_ids );
        $attribute->set_position( $position );
        $attribute->set_visible( $values['is_visible'] );
        $attribute->set_variation( $values['for_variation'] );

        $data[$taxonomy] = $attribute; // Set in an array

        $position++; // Increase position
    }
    return $data;
}

2) USAGE: - Example for a simple product creation with 2 product attributes "Color" and "Size":

$product_id = create_product( array(
    'type'               => '', // Simple product by default
    'name'               => __("The product title", "woocommerce"),
    'description'        => __("The product description…", "woocommerce"),
    'short_description'  => __("The product short description…", "woocommerce"),
    // 'sku'                => '',
    'regular_price'      => '5.00', // product price
    // 'sale_price'         => '',
    'reviews_allowed'    => true,
    'attributes'         => array(
        // Taxonomy and term name values
        'pa_color' => array(
            'term_names' => array('Red', 'Blue'),
            'is_visible' => true,
            'for_variation' => false,
        ),
        'pa_size' =>  array(
            'term_names' => array('X Large'),
            'is_visible' => true,
            'for_variation' => false,
        ),
    ),
) );  

// Displaying the created product ID
echo $product_id;

Tested and works using only Woocommerce 3 CRUD methods.

这篇关于使用 Woocommerce 3 中的 CRUD 方法以编程方式创建产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆