@alex0176

Как вывести иерархическое дерево термов в WordPress?

Есть иерархия вложенностей термов таксономии. Она может быть разной от 2 до 5 уровней вложенности. У меня есть функция которая принимает ID терма родителя и название таксономии.
Вот эта функция:

function  hierarchyTerms( $termID,  $taxonomy, )
{
     $terms_children = get_term_children( $termID, $taxonomy );

     if( ! is_wp_error( $terms_children ) && ! empty( $terms_children ) ) {

           $output = '';
           $output .= '<ul>';
           foreach ( $terms_children as $child_id ) 
           {
                $output .= '<li>'. get_term( $child_id )->name. '';
                $output .= hierarchyTerms( $child_id, $taxonomy );
		$output .= '</li>';
           }
          $output .= '</ul>';

          return $output;
    }
}

Мне нужно чтобы на выходе сформировался следующая структура HTML:

<ul>
       <li>
          Category 1
          <ul>
             <li>Cat 1.1</li>
             <li>Cat 1.2</li>
         </ul>
       </li>
      <li>
         Category 2
         <ul>
           <li>Cat 2.1</li>
        </ul>
      </li>
    </ul>

Но у меня в конце появляется дубляж термов. Видать это связано с рекурсией и областью видимости.
  • Вопрос задан
  • 139 просмотров
Решения вопроса 1
@weart
function get_categories_tree(string $taxonomy = 'category'): array
{
    $terms = get_terms([
        'taxonomy' => $taxonomy,
        'parent' => false,
        'hide_empty' => false,
    ]);

    if (empty($terms) || $terms instanceof WP_Error) {
        return [];
    }

    $categories = [];

    foreach ($terms as $term) {
        $categories[] = (object) [
            'value' => $term->term_id,
            'name' => $term->name,
            'children' => get_children_categories($term->term_id, $category_id),
        ];
    }

    return $categories;
}

function get_children_categories(int $parent_term_id, int $category_id): array
{
    $children = array();
    $child_terms = get_terms([
        'taxonomy' => 'category',
        'parent' => $parent_term_id,
        'hide_empty' => false,
    ]);

    foreach ($child_terms as $child_term) {
        $child = (object) [
            'term_id' => $child_term->term_id,
            'name' => $child_term->name,
            'value' => $child_term->term_id,
        ];

        $grandchildren = get_children_categories($child_term->term_id, $category_id);
        if (!empty($grandchildren)) {
            $child->children = $grandchildren;
        }

        $children[] = $child;
    }

    return $children;
}


$list = get_categories_tree();

Как вывести в цикле с рекурсией думаю разберетесь..
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@maksam07
function hierarchyTerms($termID, $taxonomy) {
    $terms_children = get_term_children($termID, $taxonomy);

    if (!is_wp_error($terms_children) && !empty($terms_children)) {
        $output = '<ul>'; 

        foreach ($terms_children as $child_id) {
            $term = get_term($child_id);
            $output .= '<li>' . esc_html($term->name);
            $output .= hierarchyTerms($child_id, $taxonomy);
            $output .= '</li>';
        }

        $output .= '</ul>';

        return $output;
    }

    return ''; 
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы