以编程方式创建具有新属性值的 WooCommerce 产品变体

新手上路,请多包涵

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

WooCommerce 中已经设置了变体属性。

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

如何才能做到这一点?可能吗?


更新: 我已经写了更多我希望的代码行,并尝试了很多方法来解决它,使用 woocommerce 对象,并在使用 WordPress 数据库的数据库中添加了有关术语、术语元、术语与帖子的关系的缺失数据对象 - 但没有任何东西足以让它工作。而且我无法指出我哪里出错了——这就是为什么我不能提供一个更窄的问题——stackoverflow 更适合做的事情。

原文由 Cedric 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 943
2 个回答

2020 年 1 月更新: 更改为 WC_Product 方法 get_name() 而不是 get_title()

2018 年 9 月更新: 处理分类创建 (感谢 Carl F. Corneil)

从定义的变量产品 ID 您将在下面找到一个自定义函数,该函数将添加(创建)产品变体。可变父产品需要为其设置所需的属性。

您需要提供一些信息:

  • 属性/值数组
  • Sku、价格和库存……

该数据必须存储在格式化的多维数组中 (参见最后的示例)

此函数将检查属性值(术语名称)是否已经存在,如果不存在:

  • 它为产品属性创建它
  • 将其设置在父变量产品中。

自定义函数代码:

 /**
 * 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 个属性的示例):

 $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 );

测试和工作。

第 2 部分: 在 WooCommerce 中以编程方式创建可变产品和两个新属性

你会在后端得到这个:

在此处输入图像描述

它将在前端完美运行。

相关: 在 Woocommerce 3 中使用 CRUD 方法以编程方式创建产品

原文由 LoicTheAztec 发布,翻译遵循 CC BY-SA 4.0 许可协议

被接受的文章就像一个魅力。如果您设法创建了变体,但它没有在变体中选择一个选项,并且当您尝试保存一个重置为空时,我强烈建议检查这个线程 创建 WooCommerce 产品变体添加一个空属性值,我一直在同一个问题上挣扎了2个多小时。快乐编码

原文由 pete koda 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题