以编程方式创建具有新属性值的WooCommerce产品变体 [英] Create programmatically a WooCommerce product variation with new attribute values

查看:106
本文介绍了以编程方式创建具有新属性值的WooCommerce产品变体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WooCommerce版本3+中创建了一个可变产品(父"产品).通过WordPress插件,我想以编程方式创建具有新属性值的产品变体(儿童"产品).

I have created a variable product ("parent" product) in WooCommerce version 3+. From a WordPress plugin, I would like to programmatically create the product variations ("children" product) with new attribute values.

变体属性已经在WooCommerce中设置.
因此,每次创建一个变体时,也应该以编程方式创建新属性的值,并将其设置在父变量产品中.

The variation attributes are already set in WooCommerce.
So every time one variation is created, the new attribute's values should be created programmatically too and set in the parent Variable product.

这怎么办?有可能吗?

更新:我为此写了更多的代码行,并尝试使用woocommerce对象解决了许多问题,并在其中添加了有关术语,termmeta,术语与帖子之间关系的缺失数据使用WordPress数据库对象的数据库-但没有任何措施足以使其正常工作.而且我无法指出我出了错的地方-这就是为什么我不能提供一个更狭窄的问题-堆栈溢出的原因更多.

推荐答案

更新2020年1月:更改为 WC_Product方法get_name() 而不是get_title()
2018年9月更新:处理分类法的创建(感谢卡尔·科尼埃(Carl F. Corneil))

Update January 2020: Changed to WC_Product method get_name() instead of get_title()
Update September 2018: Handling taxonomy creation (Thanks to Carl F. Corneil)

从已定义的可变产品ID中找到波纹管,这是一个自定义函数,将添加(创建)产品变体.变量父产品需要为其设置所需的属性.

From a defined variable product ID You will find bellow, a custom function that will add (create) a Product variation. The variable parent product needs to have set for it the needed attributes.

您将需要提供以下信息:

You will need to provide some information as:

  • 属性/值的数组
  • Sku,价格和库存….

此数据必须存储在格式化的多维数组中(请参阅最后的示例).

This data has to be stored in a formatted multi dimensional array (see an example at the end).

此函数将检查属性值(术语名称)是否已经存在,如果不存在: -为商品属性创建商品 -将其设置在父变量产品中.

This function will check if the attributes values (term name) already exist and if not: - it create it for the product attribute - set it in the parent variable product.

自定义功能代码:

/**
 * Create a product variation for a defined variable product ID.
 *
 * @since 3.0.0
 * @param int   $product_id | Post ID of the product parent variable product.
 * @param array $variation_data | The data to insert in the product.
 */

function create_product_variation( $product_id, $variation_data ){
    // Get the Variable product object (parent)
    $product = wc_get_product($product_id);

    $variation_post = array(
        'post_title'  => $product->get_name(),
        'post_name'   => 'product-'.$product_id.'-variation',
        'post_status' => 'publish',
        'post_parent' => $product_id,
        'post_type'   => 'product_variation',
        'guid'        => $product->get_permalink()
    );

    // Creating the product variation
    $variation_id = wp_insert_post( $variation_post );

    // Get an instance of the WC_Product_Variation object
    $variation = new WC_Product_Variation( $variation_id );

    // Iterating through the variations attributes
    foreach ($variation_data['attributes'] as $attribute => $term_name )
    {
        $taxonomy = 'pa_'.$attribute; // The attribute taxonomy

        // If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
        if( ! taxonomy_exists( $taxonomy ) ){
            register_taxonomy(
                $taxonomy,
               'product_variation',
                array(
                    'hierarchical' => false,
                    'label' => ucfirst( $attribute ),
                    'query_var' => true,
                    'rewrite' => array( 'slug' => sanitize_title($attribute) ), // The base slug
                ),
            );
        }

        // Check if the Term name exist and if not we create it.
        if( ! term_exists( $term_name, $taxonomy ) )
            wp_insert_term( $term_name, $taxonomy ); // Create the term

        $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get the term slug

        // Get the post Terms names from the parent variable product.
        $post_term_names =  wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );

        // Check if the post term exist and if not we set it in the parent variable product.
        if( ! in_array( $term_name, $post_term_names ) )
            wp_set_post_terms( $product_id, $term_name, $taxonomy, true );

        // Set/save the attribute data in the product variation
        update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug );
    }

    ## Set/save all other data

    // SKU
    if( ! empty( $variation_data['sku'] ) )
        $variation->set_sku( $variation_data['sku'] );

    // Prices
    if( empty( $variation_data['sale_price'] ) ){
        $variation->set_price( $variation_data['regular_price'] );
    } else {
        $variation->set_price( $variation_data['sale_price'] );
        $variation->set_sale_price( $variation_data['sale_price'] );
    }
    $variation->set_regular_price( $variation_data['regular_price'] );

    // Stock
    if( ! empty($variation_data['stock_qty']) ){
        $variation->set_stock_quantity( $variation_data['stock_qty'] );
        $variation->set_manage_stock(true);
        $variation->set_stock_status('');
    } else {
        $variation->set_manage_stock(false);
    }

    $variation->set_weight(''); // weight (reseting)

    $variation->save(); // Save the data
}

代码会出现在您活动的子主题(或主题)的function.php文件或任何插件文件中.

用法(带有2个属性的示例):

Usage (example with 2 attributes):

$parent_id = 746; // Or get the variable product id dynamically

// The variation data
$variation_data =  array(
    'attributes' => array(
        'size'  => 'M',
        'color' => 'Green',
    ),
    'sku'           => '',
    'regular_price' => '22.00',
    'sale_price'    => '',
    'stock_qty'     => 10,
);

// The function to be run
create_product_variation( $parent_id, $variation_data );

经过测试,可以正常工作.

Tested and works.

第2部分: 您将在后端得到它:

它将在前端完美运行.

相关: 查看全文

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