상현에 하루하루
개발자의 하루

계층 카테고리

( 업데이트: )

우리는 카테고리를 만들고 분류할 때 계층을 이용하는 경우가 많다.

그렇다면 이것을 어떻게 구현해야 하나? 이 질문 또한 오래된 질문이다.

기본적인 구현방법

워드프레스에서는 taxonomy의 아이디 이름으로 list를 출력할 수 있는 함수가 있다.

wp_list_categories이고 자세한 내용은 Codex를 참고하면 된다.

wp_list_categories() | Function | WordPress Developer Resources

이로써 간단하게 출력할 수 있다.

커스텀 카테고리 리스트

리스트형태에서 아이콘 커스텀 데이터 등등 관리자가 원하는 형태로 만들어야 하는 경우가 있다.

그렇다면 각각의 term에 custom data를 등록하고 가져오게된다.

그렇다면 이 것을 어떻게 구현해야할까?

일단 계층을 이루는 데이터를 가져온다.

Get 계층 데이터

get_terms()를 통해서 taxonomy의 아이디로 terms의 데이터를 가져올 수 있다. 하지만 이렇게 가져온 데이터는 부모를 계층적으로 분류해주지 않고 parent라는 속성으로 어떤 부모를 가졌는지만 확인할 수 있다.

filter 계층 데이터로 가공

계층적인 구조로 만들어준다. parent 데이터 아래 child 값으로 리스트를 넣어서 만든다.

/**
 * Recursively sort an array of taxonomy terms hierarchically. Child categories will be
 * placed under a 'children' member of their parent term.
 * @param Array   $cats     taxonomy term objects to sort
 * @param Array   $into     result array to put them in
 * @param integer $parentId the current parent ID to put them in
 */

function sort_terms_hierarchically(Array &$cats, Array &$into, $parentId = 0)
{
    foreach ($cats as $i => $cat) {
        if ($cat->parent == $parentId) {
            $into[$cat->term_id] = $cat;
            unset($cats[$i]);
        }
    }

    foreach ($into as $topCat) {
        $topCat->children = array();
        sort_terms_hierarchically($cats, $topCat->children, $topCat->term_id);
    }
}Code language: PHP (php)

사용법은 다음과 같이 사용

$categories = get_terms('my_taxonomy_name', array('hide_empty' => false));
$categoryHierarchy = array();
sort_terms_hierarchically($categories, $categoryHierarchy);

var_dump($categoryHierarchy);Code language: PHP (php)

위 데이터로 만든 Array

array(21) {
  [171]=>
  object(WP_Term)#2651 (12) {
    ["term_id"]=>
    int(171)
    ["name"]=>
    string(4) "HTML"
    ["slug"]=>
    string(4) "html"
    ["term_group"]=>
    int(0)
    ["term_taxonomy_id"]=>
    int(171)
    ["taxonomy"]=>
    string(12) "dev_category"
    ["description"]=>
    string(0) ""
    ["parent"]=>
    int(0)
    ["count"]=>
    int(1)
    ["filter"]=>
    string(3) "raw"
    ["term_order"]=>
    string(1) "0"
    ["children"]=>
    array(0) {
    }
  }
  [167]=>
  object(WP_Term)#2647 (12) {
    ["term_id"]=>
    int(167)
    ["name"]=>
    string(3) "CSS"
    ["slug"]=>
    string(3) "css"
    ["term_group"]=>
    int(0)
    ["term_taxonomy_id"]=>
    int(167)
    ["taxonomy"]=>
    string(12) "dev_category"
    ["description"]=>
    string(0) ""
    ["parent"]=>
    int(0)
    ["count"]=>
    int(2)
    ["filter"]=>
    string(3) "raw"
    ["term_order"]=>
    string(1) "1"
    ["children"]=>
    array(1) {
      [168]=>
      object(WP_Term)#2660 (12) {
        ["term_id"]=>
        int(168)
        ["name"]=>
        string(4) "SCSS"
        ["slug"]=>
        string(4) "scss"
        ["term_group"]=>
        int(0)
        ["term_taxonomy_id"]=>
        int(168)
        ["taxonomy"]=>
        string(12) "dev_category"
        ["description"]=>
        string(0) ""
        ["parent"]=>
        int(167)
        ["count"]=>
        int(2)
        ["filter"]=>
        string(3) "raw"
        ["term_order"]=>
        string(2) "27"
        ["children"]=>
        array(0) {
        }
      }
    }
  }
 …Code language: PHP (php)

이제 sort_terms_hierarchically 함수에서 각각 term을 순회할때 가공할 커스텀 필드의 데이터를 가져와서 넣어주면 된다.

그리고 php 파일로 리스트를 만들어주면 끝!

왼쪽: sort_terms_hierarchically
오른쪽: wp_list_categories

참고