如何以编程方式更新产品属性?

问题描述 投票:0回答:2

我使用以下代码向产品添加属性:

foreach ($_attributes as $name => $value) {
        wp_set_object_terms($post_id, $value, $name, true);
        $product_attributes[$name] = array (
            'name' => $name, // set attribute name
            'value' => $value, // set attribute value
            'is_visible' => 0,
            'is_variation' => 1,
            'is_taxonomy' => 1
        );
    }
update_post_meta($post_id, '_product_attributes', $product_attributes );

但它删除了我在管理中的产品编辑中添加的先前属性,例如产品品牌或型号。 如何更新当前产品属性而不删除以前的产品属性?

谢谢你帮助我。

wordpress woocommerce plugins
2个回答
3
投票

您可以在更新之前简单地备份数据库内容,如下所示:

$tmpBk = get_post_meta($post_id, '_product_attributes',true);
update_post_meta($post_id, '_product_attributes', array_merge(tmpBk,$product_attributes) );

这应该足以保存您之前存储的值


0
投票

我假设您尝试保存分配给分类的产品属性(代码中的

'is_taxonomy' => 1
)。

更新链接到分类的产品属性

如果需要更新设置了taxonomy_id的属性的选项,不幸的是,仅保存产品是不够的。

假设您有一个产品属性

pa_color

object(WC_Product_Attribute)[26022]
  protected 'data' => 
    array (size=6)
      'id' => int 5
      'name' => string 'pa_color' (length=8)
      'options' => 
        array (size=2)
          0 => int 185
          1 => int 186
      'position' => int 0
      'visible' => boolean true
      'variation' => boolean true

您想要添加 term_id 187 的第三个选项。不幸的是,您在更新此处的选项时必须应用解决方法。

// retrieve the product
$product = wc_get_product( 3710 );

// get all attributes
$attributes = $product->get_attributes();

// make a copy from the attribute to be updated
$pa_color   = $attributes['pa_color'];

// delete pa_color from the attributes
unset( $attributes['pa_color'] );

// set the attributes without pa_color
$product->set_attributes( $attributes );

// save the product
$product->save();

// set your new options for pa_color
$pa_color->set_options( [ 185, 186, 187 ] );

// add the WC_Product_Attribute object back again
$attributes['pa_color'] = $pa_color;

// set the attributes, now with pa_color in it
$product->set_attributes( $attributes );

// save it again
$product->save();

为什么要采取解决方法?

底层

WC_Product
类中的
changes
属性无法识别 WooCommerce 中
WC_Data
对象上的设置属性。

通过使用

$product->save()
,WooCommerce 检查对象是否发生更改,并在此方法中创建
$changeset
。仅设置嵌套在对象中太深的属性选项,平面更改筛选无法识别。请参阅 woocommerce 存储库中的代码行: https://github.com/woocommerce/woocommerce/blob/319408bb67edc8ea0ab1c6abb04a14b9e65b76ab/plugins/woocommerce/includes/abstracts/abstract-wc-product.php#L1441

© www.soinside.com 2019 - 2024. All rights reserved.