如何在 WooCommerce 中使用现有的产品属性而不使用 WC_Product_Attribute 类创建新属性?

Ahm*_*ibi 5 wordpress woocommerce

我正在尝试创建一个以编程方式创建可变产品的 Wordpress 插件,但问题是,我想使用之前从管理仪表板手动定义的属性。我需要将属性分配给我正在创建的产品。

这是我正在使用的代码(不是我的,我从这个答案中得到它:以编程方式创建可变产品和 WooCommerce 中的两个新属性

function addProduct(){
    //Create main product
    $product = new WC_Product_Variable();

    //Create the attribute object
    $attribute = new WC_Product_Attribute();

    //pa_size tax id
    $attribute->set_id( 0 ); // -> SET to 0

    //pa_size slug
    $attribute->set_name( 'Couleur' ); // -> removed 'pa_' prefix

    //Set terms slugs
    $attribute->set_options( array(
        'Noir'
    ) );

    $attribute->set_position( 0 );

    //If enabled
    $attribute->set_visible( 1 );

    //If we are going to use attribute in order to generate variations
    $attribute->set_variation( 1 );

    $product->set_attributes(array($attribute));

    //Save main product to get its id
    $id = $product->save();

    $variation = new WC_Product_Variation();
    $variation->set_regular_price(10);
    $variation->set_parent_id($id);

    //Set attributes requires a key/value containing
    // tax and term slug
    $variation->set_attributes(array(
        'Couleur' => 'Noir' // -> removed 'pa_' prefix
    ));

    //Save variation, returns variation id
    echo get_permalink ( $variation->save() );


    // echo get_permalink( $id ); // -> returns a link to check the newly created product   
}
Run Code Online (Sandbox Code Playgroud)

产品已正确创建,但代码创建了一个新属性并将其称为“Couleur”,而不是使用我已经定义的“Couleur”属性。

提前致谢。

Vin*_*ano 3

WooCommerce 允许您使用全局属性和产品级 (本地或自定义)属性。

\n

全局属性适用于所有产品。当您删除该属性的术语时,对于将该属性与该术语一起使用的所有产品,该属性都会被删除。相反,当您添加新术语时,它将可用于所有其他产品。

\n
\n

全局属性您可以在 Wordpress 仪表板 > 产品 >\n属性中找到它们。

\n
\n

产品级 (本地或自定义)属性仅为该产品定义,不可用于其他产品。

\n
\n

产品级属性只能在产品\n编辑页面的“属性”部分中找到。

\n
\n

您可以在这里找到更多详细信息:

\n\n

解决方案

\n

通过编程,您需要将前缀添加pa_到每个属性段。

\n

此外,您还将 id 设置为零:$attribute->set_id( 0 );但通过这样做,您正在设置产品级(而不是全局)属性。您需要将此行更改为:

\n
// get a product attribute ID by name.\n$attribute_id = wc_attribute_taxonomy_id_by_name( \'Couleur\' );\n$attribute->set_id( $attribute_id );\n
Run Code Online (Sandbox Code Playgroud)\n

您应该使用this而不是使用此答案

\n

有用的链接

\n\n