Программно вывести термины словаря в виде дерева с подсчётом количества материалов
Код:
/**
* Return rendered taxonomy tree
*/
function mymodule_taxonomy_tree($vid) {
$terms = db_query("
SELECT td.tid, td.name, th.parent, (
SELECT COUNT(*) FROM {taxonomy_index} ti
LEFT JOIN {node} n ON ti.nid = n.nid
WHERE ti.tid = td.tid AND n.status = 1
) node_count FROM {taxonomy_term_data} td
INNER JOIN {taxonomy_term_hierarchy} th ON th.tid = td.tid
WHERE vid = :vid
ORDER BY weight
", array(':vid' => $vid))->fetchAll();
return theme('item_list', array('items' => _mymodule_taxonomy_tree($terms)));
}
/**
* Helper for mymodule_taxonomy_tree()
*/
function _mymodule_taxonomy_tree($terms, $parent = 0, &$node_count = 0) {
$items = array();
$node_count = 0;
foreach ($terms as $term) {
if ($term->parent == $parent) {
$children = _mymodule_taxonomy_tree($terms, $term->tid, $childs_node_count);
$node_count += $term->node_count + $childs_node_count;
$items[] = array(
'data' => l($term->name, 'catalog/' . $term->tid) . ' (' . ($term->node_count + $childs_node_count) . ')',
'children' => $children,
);
}
}
return $items;
}
Использование:
echo mymodule_taxonomy_tree(1);
Для вывода плоского списка можно воспользоваться Views — Как с помощью Views 3 вывести список терминов с количеством помеченных ими нод.
Написанное актуально для
Drupal 7
Комментарии:
Нету комментариев для вывода...