2014-11-04 8 views
0

woocommerce의 3 가지 깊이 범주 구조에서 두 번째 수준 범주 만 얻으려고합니다.두 번째 수준의 woocommerce 제품 범주 만 가져올 수 없습니다.

하지만 항상 3 단계를 반환합니다.

/** 
* Get second level cat 
*/ 
function get_second_cat_level($parent_id) { 
    $subcats = array(); 
    $args = array(
     'parent'  => $parent_id, 
     'taxonomy'  => 'product_cat', 
     'orderby'  => 'name', 
     'show_count' => 0, 
     'pad_counts' => 0, 
     'hierarchical' => 1, 
     'hide_empty' => 0 
     ); 
    $cats = get_categories($args); 

    foreach ($cats as $cat) { 
     $subcats[] = $cat; 
     var_dump($cat); 
    } 

    return $cats; 
} 

나는 $parent_id이 parent_category의 문자열 ID라고 가정합니다. 이것은 단지 미친 짓입니다.

답변

0

아무도 나를 위해 해결책이없는 것 같아서, 내가 사용한 하나의 솔루션을 공유 할 것입니다. 그러나주의 깊으십시오, 이것은 3 개의 깊이 수준 종류 그룹에 아주 특정입니다.

function get_product_category($field, $value) { 
    $authorized_fields = array(
     'term_id', 
     'name', 
     'slug' 
    ); 
    // Check if field and value are set and not empty 
    if (!isset($field) || empty($field) || !isset($value) || empty($value)) { 
     $response = "Error : check your args, some are not set or are empty."; 
    } 
    else { 
     // Check if the specified field is part of the authorised ones 
     if (!in_array($field, $authorized_fields)) { 
      $response = "Unauthorised field $field";  } 
     else { 
      // init exists var to determine later if specified value matches 
      $exists = false; 
      $product_cats = get_terms('product_cat', array(
       'hide_empty' => 0, 
       'orderby' => 'name' 
      )); 
      // the loop will stop once it will have found the matching value in categories 
      foreach ($product_cats as $product_cat) { 
       if($product_cat->$field == $value) { 
        $response = $product_cat; 
        $exists = true; 
        break; 
       } 
      } 
      if ($exists == false) { 
       $response = array(
        "message" => "Error with specified args", 
        "field" => "$field", 
        "value" => "$value" 
       ); 
      } 
     } 
    } 
    return $response; 
} 

번째 함수는 두번째 레벨 카테고리 반환 제를 사용 하나의 ID로부터 분류 개체 슬러그 또는 특정 카테고리의 이름을 얻을 :

는 I 2 개 함수를 작성한 . 인수가 $dep인데, false로 단독 테스트 된 경우 다른 곳에서 필요한 다른 결과가 반환됩니다. 그러니주의를 기울이지 마십시오.

function get_first_child_cat_only ($cat_id, $dep = true) { 
    // Array which handle all the 2nd child sub cats 
    $subcats = array(); 
    // $cat_id is the parent (1st level) cat id 
    $categories = get_term_children($cat_id, 'product_cat'); 
    foreach ($categories as $sub_category) { 
     if ($dep == true && get_term_children($sub_category, 'product_cat')) { 
      $subcats[] = get_product_category('term_id', $sub_category); 
     } 
     elseif($dep == false) { 
      $subcats[] = get_product_category('term_id', $sub_category); 
     } 
    } 
    return $subcats; 
} 

작은 설명 : 위 함수는 하위 카테고리가있는 하위 카테 고리 만 반환합니다. 따라서 자식이 없으며 두 번째 자식 만 반환하는 마지막 자식 (세 번째 자식)은 무시됩니다.

이것은 분명히 향상 될 수 있습니다. 아마 나는 아마도 "비판"을받을 것이고, 사실 그렇게 희망합니다! 그러니 망설이지 말라.

관련 문제