2016-01-06 44 views
2

我正在嘗試爲我的woocommerce網站設置類別的分層列表。這是很難描述,但是我有什麼與此類似的產品類別的東西...獲取整個類別的層次結構

Animals 
-Dog 
    --Beagle 
    --Poodle 
-Cat 
-Rabbit 
Cars 
-Chevy 
-Toyota 
People 
Cities 
Planets 

如果我期待在貴賓犬頁我想顯示這是我的類別列表..

Animals 
-Dog 
    --Beagle 
    --Poodle 

這裏是我目前代碼..

<?php 
$args = array( 
    'taxonomy' => 'product_cat', 
    'hide_empty' => false, 
    'child_of' => get_queried_object()->term_id, 
    //'child_of' => 6, 
    'title_li' => __('Categories'), 
    'depth' => 3 
); 

wp_list_categories($args); 
?> 

我能夠完成這項工作,如果我設置child_of特定單詞ID(上面註釋)。但我希望這可以自動工作。基本上我需要通過所有類別循環,並從最高級別類別開始列出條款。

它幾乎就像顯示麪包屑一樣,但顯示了第一級別類別下的所有兒童類別。

+0

加上一個使用'get_queried_object()' –

回答

0

有你應該有興趣在其中你從get_queried_object()回來術語對象的兩個屬性,這是

  • term_id這是長期

  • parent的ID這是一個該項的父項的整數值。這個值是0如果術語是頂層或任何其它的整數值等於當前術語父級的術語ID

考慮到這一點,我們可以使用parent以確定正在觀看的術語是層次結構中的頂級術語或較低的術語。這隻能解決一半的問題,因爲我們仍然不知道何時parent不是0如果該術語是子女或孫子任期。爲了確定這一點,我們將使用get_ancestors()來獲取當前術語的所有層次結構,並從那裏我們可以得到頂級項

get_ancestors()回收期ID數組,最後一個ID爲頂級項和第一編號是通過的術語的直接父母。對於頂級術語,將返回一個空數組。由於這裏有開銷,我們將首先檢查當前期限是否爲頂級期限,然後我們運行get_ancestors()

對於大塊代碼,我總是可以更容易地編寫一個適當的包裝函數,我可以打電話到我的模板,因爲需要,所以可以讓代碼的功能

/** 
* Function to display all terms from a given taxonomy in a hierarchy 
* 
* @param (array) $args Array of valid parameters for wp_list_categories 
*/ 
function custom_term_list($args = []) 
{ 
    // Make sure that this is a taxonomy term archive for the ttaxonomy 'product_cat', if not, return 
    if (!is_tax('product_cat')) 
     return; 

    // Get the current term object 
    $term = get_queried_object(); 

    // Check if current term is top level or not 
    if (0 == $term->parent) { 
     // Show all terms in hierarchy below the current term 
     $parent = $term->term_id; 
     // If you need to show all terms regardless, you can do the following 
     //$parent = 0; 
    } else { // Term is not top level 
     $hierarchy = get_ancestors($term->term_id, $term->taxonomy); 
     $parent = end($hierarchy); 
    } 

    // Make sure we override `child_of` if it is set by the user 
    $args['child_of'] = $parent; 
    // Make sure we set the taxonomy to the term object's taxonomy property 
    $args['taxonomy'] = $term->taxonomy; 

    wp_list_categories($args); 
} 

我們就來看看如何使用功能,幾個音符之前:

  • 的代碼是未經測試,可能是馬車。一定要首先在本地與調試設置爲true

  • 代碼testthis至少需要PHP 5.4

  • 我寫的代碼對分類product_cat的分類存檔頁面唯一的工作。您不需要將該分類法傳遞給該函數,並且該分類法來自術語對象。但是,您可以修改代碼以使用任何分類標準

  • 我已經編寫了代碼,如果用戶設置了child_of參數,則不會使用該值。該功能將覆蓋該值

讓我們看看用例。您可以使用該功能如下:(代碼從OP使用)

$args = [ 
    'hide_empty' => false, 
    'title_li' => __('Categories'), 
    'depth'  => 3 
]; 
custom_term_list($args); 
+0

這是完美的。謝謝! – Dustin

+0

我的榮幸,很高興它解決了。享受;-) –

+0

@PieterGoosen,我如何通過出售獲得所有類別?我需要最暢銷的類別。請幫忙 –