如何使用现有产品属性以编程方式创建可变产品

问题描述

任何建议将不胜感激。 我有以下代码创建了可变产品,但没有附加属性(以及变体)。

$new_variable_product = new WC_Product_Variable();
 $new_variable_product->set_name("Book Your Event");
 $new_variable_product->set_slug($permalink);
 $new_variable_product->set_short_description('Hello world');
 $new_variable_product->set_status('publish');
 $new_variable_product->save();
 //*************************//
    $attribute = new WC_Product_Attribute();
    
    // get a product attribute ID by name.
    $attribute_id = wc_attribute_taxonomy_id_by_name( 'Event Purpose' );
    $attribute->set_id( $attribute_id );
    $attribute->set_name( 'pa_type-of-event' ); // -> removed 'pa_' prefix
    
    //Set terms slugs
    $attribute->set_options( array(
        'Hens Party','Social Party','Team Building'
    ) );
    $attribute->set_position( 0 );
    $attribute->set_visible( 1 );//If enabled
    $attribute->set_variation( 1 );//If we are going to use attribute in order to generate variations
    
    //Create the attribute2 object
    $attribute2 = new WC_Product_Attribute();
    
    // get a product attribute ID by name.
    $attribute_id = wc_attribute_taxonomy_id_by_name( 'Estimated Guest No' );
    $attribute2->set_id( $attribute_id );
    $attribute2->set_name( 'pa_participants' ); // -> removed 'pa_' prefix
    
    //Set terms slugs
    $attribute2->set_options( array(
        '1','2','3','4','5','6','7','8','9','10'
    ) );
    $attribute2->set_position( 0 );
    $attribute2->set_visible( 1 );//If enabled
    $attribute2->set_variation( 1 );//If we are going to use attribute in order to generate variations
    
    $new_variable_product->set_attributes(array($attribute,$attribute2));
    
    //Save main product to get its id
    $thisid = $new_variable_product->save();
    
    $variation = new WC_Product_Variation();
    $variation->set_regular_price($price);
    $variation->set_parent_id($thisid);
    
    //Set attributes requires a key/value containing
    // tax and term slug
    $variation->set_attributes(array(
        'pa_type-of-event' => '','pa_participants' => ''
    ));
    $variation->save(); 

具有名称的现有属性,如下所示。

enter image description here

我注意到这一行

$attribute_id = wc_attribute_taxonomy_id_by_name( 'Event Purpose' );

将 $attribute_id 返回为 0。为什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)