2017-09-05 11 views

답변

1

1)은 각 변수 제품에 대한 귀하의 json 데이터와 같은 배열이 조각 삽입해야합니다

 "variations_default_attributes": 
     [ 
      { 
       "size" : "Medium", 
       "color" : "Blue" 
      } 
     ] 

또는

"variations_default_attributes": 
    { 
     "size" : "Medium", 
     "color" : "Blue" 
    } 

이 배열은 속성 하녀입니다 짧은 슬러그 ('pa_'제외) 및 기본 용어 값.

2) 그런 다음 전용 기능 :

function insert_variations_default_attributes($post_id, $products_data){ 
    foreach($products_data as $attribute => $value) 
     $variations_default_attributes['pa_'.$attribute] = get_term_by('name', $value, 'pa_'.$attribute)->slug; 
    // Save the variation default attributes to variable product meta data 
    update_post_meta($post_id, '_default_attributes', $variations_default_attributes); 
} 

3) 당신은이 기능이 마지막에 한 줄을 추가 트리거해야합니다

function insert_product ($product_data) 
{ 
    $post = array(// Set up the basic post data to insert for our product 

     'post_author' => 1, 
     'post_content' => $product_data['description'], 
     'post_status' => 'publish', 
     'post_title' => $product_data['name'], 
     'post_parent' => '', 
     'post_type' => 'product' 
    ); 

    $post_id = wp_insert_post($post); // Insert the post returning the new post id 

    if (!$post_id) // If there is no post id something has gone wrong so don't proceed 
    { 
     return false; 
    } 

    update_post_meta($post_id, '_sku', $product_data['sku']); // Set its SKU 
    update_post_meta($post_id,'_visibility','visible'); // Set the product to visible, if not it won't show on the front end 

    wp_set_object_terms($post_id, $product_data['categories'], 'product_cat'); // Set up its categories 
    wp_set_object_terms($post_id, 'variable', 'product_type'); // Set it to a variable product type 

    insert_product_attributes($post_id, $product_data['available_attributes'], $product_data['variations']); // Add attributes passing the new post id, attributes & variations 
    insert_product_variations($post_id, $product_data['variations']); // Insert variations passing the new post id & variations 

    ## Insert variations default attributes passing the new post id & variations_default_attributes 
    insert_variations_default_attributes($post_id, $products_data['variations_default_attributes']);  
} 

코드는 function.php 파일에 간다 활성 어린이 테마 (또는 테마) 또는 모든 플러그인 파일에서도 사용할 수 있습니다.

이 코드는 테스트되었으며 작동합니다.

+1

감사합니다 :) –

+0

시도 update_post_meta ($ post_id, '_default_attributes', $ variations_default_attributes); wc3.0에서는 이것이 작동하지 않습니다. 그래서 나는 다음을 시도했다 : $ standardValArr = array(); $ standardValArr [ 'pa_groesse'] = 'M'; $ parent_product-> set_default_attributes ($ standardValArr); 불행히도 이것은 작동하지 않습니다. –

+0

@JanineKroser 당신은 무엇을하려고합니까? 문제 또는 귀하의 문제는 무엇입니까? 이 대답은 당신에게 편리하지 않을 수도 있으므로 새로운 질문을해야 할 수도 있습니다. – LoicTheAztec