【问题标题】:WooCommerce: Add a product attribute to the existing ones in a productWooCommerce:将产品属性添加到产品中的现有属性
【发布时间】:2018-05-04 23:11:21
【问题描述】:

我正在努力为产品添加属性。

我有一组关键字要添加到产品中:

$clean_keywords = array('cake','cup cakes');
$term_taxonomy_ids = wp_set_object_terms( get_the_ID(), $clean_keywords, 'pa_keywords', true );
$thedata = Array('pa_keywords' => Array(
    'name' => 'pa_keywords',
    'value' => '',
    'is_visible' => '0',
    'is_taxonomy' => '1'
));

update_post_meta( get_the_ID(),'_product_attributes',$thedata);

这很好用,但它会删除我附加到产品的所有其他属性。

我认为解决方案是获取当前属性并将其与$thedata 变量合并...但不确定如何执行此操作。

有什么想法吗?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce attributes product


    【解决方案1】:

    您需要先获取现有产品属性,然后将新产品属性插入到数组中,然后再保存。我还在数组中添加了 2 个缺失的参数……

    所以你的代码应该是:

    $product_id = get_the_ID();
    $taxonomy = 'pa_keywords';
    $clean_keywords = array('cake','cup cakes');
    $term_taxonomy_ids = wp_set_object_terms( $product_id, $clean_keywords, $taxonomy, true );
    
    // Get existing attributes
    $product_attributes = get_post_meta( $product_id, '_product_attributes', true);
    
    // get the count of existing attributes to set the "position" in the array
    $count = count($product_attributes);
    
    // Insert new attribute in existing array of attributes (if there is any)
    $product_attributes[$taxonomy] = array(
        'name' => $taxonomy,
        'value' => '',
        'position' => $count, // added
        'is_visible' => '0',
        'is_variation' => '0', // added (set the right value)
        'is_taxonomy' => '1'
    );
    
    // Save the data
    update_post_meta( $product_id, '_product_attributes', $product_attributes );
    

    现在应该可以在不删除现有数据的情况下工作。

    【讨论】:

    • 刚刚知道怎么做...再次感谢
    猜你喜欢
    • 2019-07-11
    • 2017-11-24
    • 2017-06-26
    • 2022-08-19
    • 2014-08-14
    • 1970-01-01
    • 2022-12-17
    • 2019-01-23
    • 2020-06-18
    相关资源
    最近更新 更多