在 Drupal 實作以 taxonomy 為基礎的導覽介面

如果想要在 Drupal 裡頭實作類似網站目錄 (Web directory) 的資訊架構(如 Yahoo!, Open Directory Project (DMOZ) 等),較適合的組織方式為使用 taxonomy 對各 node 賦予分類標題。

但是,這樣帶來的問題是,taxonomy 本身可以 vocabulary 為單位建立一套分類樹,但是卻缺乏如 book 那樣的階層式導覽介面,為此,本文介紹、記錄個人解決這問題的經驗。

對於 Drupal 有一定熟稔程度的 power users 或 developers 可能會說,使用 Views 就能解決這問題,但是以 taxonomy 來說,最上層那個「大分類」在使用者看起來只是一個分類標題,但是在 taxonomy 內部設計裡,這個「大分類」其實是這些 taxonomy terms 的分類「總彙」(vocabulary)。若要做一套 directory,就常需要建立好幾個 vocabulary,可惜 Views 當中是以 term 為單位,我無法單獨使用 Views 選出 term 上層所屬的 vocabularies。

針對這點,我是在首頁或分類目錄頁最上層,新增幾個 PHP code 區塊,針對 taxonomies 處理的不同內容類型,列出 vocabularies 以及底下的第一層 taxonomy terms:

$vocabulary_type = "your_specific_content_type"
 
$vocabulary_items = array();
$vocabularies = taxonomy_get_vocabularies($type = $vocabulary_type);
 
foreach ($vocabularies as $vocabulary) {
$taxonomy_terms = taxonomy_get_tree($vocabulary->vid, $parent = 0, $depth = -1, $max_depth = 1);
$children = array();
 
foreach ($taxonomy_terms as $taxonomy) {
$taxonomy_nodes = taxonomy_term_count_nodes($taxonomy->tid, $type = 0);
if ($taxonomy_nodes != 0) {
$children[] = l("$taxonomy->name  ($taxonomy_nodes)", taxonomy_term_path($taxonomy));
}
}
 
$vocabulary_items[] = array(
'data' => $vocabulary->name,
'children' => $children
);
}
print theme_item_list($vocabulary_items, $title = NULL, $type = 'ul', $attributes = NULL);

每種不同的內容類型(含使用 CCK 自訂的內容類型在內)可以用同樣的程式碼,只需更動開頭的 $vocabulary_type,即可選出不同的所屬 vocabularies 以及底下的第一層 taxonomy terms。

再來裝上 Taxonomy Breadcrumb 模組,讓 breadcrumb 導覽列改以 taxonomy based。

之後還要解決一個問題,如果某個 term 底下尚有子 terms,這時就可以用 Views 做一個區塊將它們列出來。在 Relationships 這邊,為了將當前所在的 term id 當成親代 term 來使用,所以添加一個 Parent term 關係。再到 Arguments 這邊添加 Term ID,然後指定 Relationship 為剛剛選的 Parent term。

如此,假設在 http://yourdrupalsite/tanoxomy/term/12 底下,此時這個 Term ID 12 就可以當成上層 Term ID 參數,傳入這個 View,讓它去跑後端包裝起來的 SQL,選出 taxonomy/term/12 底下的 sub-terms。

接著再去 Fields 底下,指定要顯示 Term。此時這個用 Views 生出的區塊,就能顯示子分類。


已發佈

分類:

作者:

標籤:

留言

在〈在 Drupal 實作以 taxonomy 為基礎的導覽介面〉中有 6,886 則留言

  1. 「KerKer」的個人頭像
    KerKer

    板大現在的版面就很有 Drupal 的 fu~