2016-02-17 132 views
1

我以编程方式创建woocommerce变量产品。成功创建单个属性(大小),但现在我试图创建另一个属性(颜色)。我有我的形式这个属性数组。Woocommerce以编程方式创建可变产品多个属性

Array 
(
    [0] => size 
    [1] => color 
) 

,这里是我试过的代码:

 $args_t = array(
       'orderby' => 'name', 
       'order' => 'ASC', 
       'hide_empty' => true, 
       'fields' => 'names' 
      ); 

     if ($product_attributes) { 
      foreach ($product_attributes as $attr) { 
       $avail_attributes = array(); 
       $avail_attributes = get_terms(wc_attribute_taxonomy_name($attr), $args_t); 
       $attr = 'pa_'.$attr; 
       wp_set_object_terms($new_product_id, $avail_attributes, $attr); 
       $thedata = array(); 
       $thedata = Array($attr => Array(
         'name' => $attr, 
         'value' => '', 
         'postion' => '0', 
         'is_visible' => '1', 
         'is_variation' => '1', 
         'is_taxonomy' => '1' 
       )); 
       update_post_meta($new_product_id, '_product_attributes', $thedata); 
      } 
     } 

这是现状的截图:

enter image description here

回答

2

有代码中的问题..明显的一个是你正在更新foreach循环中的post meta。使它覆盖当前值直到最后一个值。请尝试下面的代码。

if ($product_attributes) { 
     $thedata = array(); 
     foreach ($product_attributes as $attr) { 
      $avail_attributes = array(); 
      $avail_attributes = get_terms(wc_attribute_taxonomy_name($attr), $args_t); 
      $attr = 'pa_'.$attr; 
      wp_set_object_terms($new_product_id, $avail_attributes, $attr); 
      $thedata[sanitize_title($attr)] = Array(
        'name' => wc_clean($attr), 
        'value' => '', 
        'postion' => '0', 
        'is_visible' => '1', 
        'is_variation' => '1', 
        'is_taxonomy' => '1' 
      ); 
     } 
     update_post_meta($new_product_id, '_product_attributes', $thedata); 
    } 
+1

太棒了!有用。其实我的不好。非常感谢 –

+0

不客气@MahaDev – Reigel

相关问题