2015-05-19 83 views
0

我正在爲一家像這樣的結構的公司製作零售商名單。 你首先列出一個擁有零售商的城市。 這是由我所做的簡單稱爲「零售商」的自定義帖子類型連接,然後我對此自定義帖子類型進行了分類,其中國家作爲父項和城市作爲子項。WordPress的:顯示類別及其子女

Country 1 
-- City 1 
--- Retailer 1 
--- Retailer 2 
-- City 2 
--- Retailer 3 
--- Retailer 4 
Country 2 
-- City 3 
--- Retailer 5 
-- City 4 
---- Retailer 6 

的事情是我堅持,不能顯示更多的不僅僅是城市和零售商,我希望能夠以包括國家,使它們在循環顯示爲好。我如何添加代碼以便從分類中獲得父項?

這是我的循環代碼

$args = array('post_type' => 'drsj_retailer', 'posts_per_page' => -1); 
$loop = new WP_Query($args); 

$allCities = array(); 

while ($loop->have_posts()) : $loop->the_post(); 

    $post_id = get_the_ID(); 
    $args = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all'); 
    $terms = wp_get_post_terms($post_id, 'retailer_city', $args); 

    $store = array(); 
    $store['title'] = get_the_title(); 
    $store['adress'] = get_field('reseller_adress'); 
    $store['phone'] = get_field('reseller_phone'); 
    $store['website'] = get_field('reseller_website'); 

    $allCities[$terms[0]->name][] = $store; 

endwhile; 

foreach($allCities as $cityName => $stores) { 
    echo "<div class='resellerEntry'>"; 
    echo "<h3 class='retailerCityTitle'>" . $cityName . "</h3>"; 

    foreach($stores as $store) { 
     echo "<p>" . $store['title'] . "&nbsp;"; 
     echo "" . $store['adress'] . "&nbsp;"; 
     echo "" . $store['phone'] . "&nbsp;"; 
     echo "<a href='http://" . $store['website'] . "' target='_blank'>" . $store['website'] . "</a></p>"; 
    } 

    echo "</div>";     
} 

當前列表中的圖片: enter image description here

圖片的分類結構: enter image description here

回答

0

嘗試這個

<?php 

//***----------------Parent cat args---------------------***/ 
$Parentcatargs = array(
    'orderby' => 'name', 
    'order' => 'ASC', 
    'use_desc_for_title' => 1, 
    'hide_empty' => 0, 
    'parent' => 0 
); 

$category = get_categories($Parentcatargs); 
//print_r($category); //Return Array 

foreach ($category as $Parentcat) { 

    echo $Parentcat->name . "<br>"; //Get Parent Category Name 

    //***----------------child cat args---------------------***/  
    $childargs = array(
     'child_of' => $Parentcat->cat_ID, 
     'hide_empty' => 0, 
     'parent' => $Parentcat->cat_ID 
    ); 


    $childcategories = get_categories($childargs); 
    //print_r($childcategories); //Return Array 

    foreach ($childcategories as $childcat) { 
     echo $childcat->name . "<br>"; //Get child Category Name 
    } 
} 
?> 

有用的鏈接:https://codex.wordpress.org/Function_Reference/get_categories

+0

我試過這個 - 但它沒有正常工作,它只顯示了「未分類」類別的名稱與wordpress,我得到PHP錯誤在這一行,$孩子是一個未定義變量。 「echo $ child-> name。」
「; // Get child Category Name」 – Fruxelot

+0

對不起。代碼爲乳香的 。 請再試一次。 –

+0

我認爲這是非常接近 - 現在它向我展示了父類別「未分類」和我分配給它的一個子類別。但我想我需要添加id的類別或可能是我使用的分類,以便我得到正確的類別。 – Fruxelot