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

标签 php wordpress woocommerce product product-variations

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

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

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


更新:我已经写了更多我希望的代码行,并尝试了很多方法来解决它,使用 woocommerce 对象,并添加了关于术语、termmeta、术语与帖子的关系的缺失数据,在使用 WordPress 数据库对象的数据库 - 但没有什么足以使其工作。而且我无法确定哪里出了问题 - 这就是为什么我无法提供更窄的问题 - stackoverflow 更适合的问题。

最佳答案

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 您将在下面找到一个将添加(创建)产品变体的自定义函数。可变父产品需要为其设置所需的属性。

您需要提供一些信息:

  • 属性/值数组
  • 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 );

经过测试并有效。

Part 2: Create programmatically a variable product and two new attributes in WooCommerce

你会在后端得到这个:

enter image description here

而且它将在前端完美运行。

Related: Create programmatically a product using CRUD methods in Woocommerce 3

关于php - 以编程方式创建具有新属性值的 WooCommerce 产品变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47518280/

相关文章:

php - 变音符号敏感搜索 PHP

php - 我的侧边栏小部件在 Wordpress 中不是垂直的?如何正确对齐?

php - 删除 woocommerce 简短描述字段

php - Woocommerce 添加到购物车将整个库存添加到购物车

php - 在 codeigniter 中一次更新两个表

php - 对自页面的 Ajax 请求不起作用

php - 如何删除mysql中的数据库并导出同名数据库?

css - 我怎样才能让这些社交分享者的风格正确?

php - 如何在 Wordpress 中使用图像 ID 数组显示分页图像?

woocommerce - 通过 API 从 WooCommerce 向外部系统发送订单详细信息