2016-12-02 24 views
1

這裏的唯一項目就是一個例子循環:計數和/或僅列出一個WordPress循環

$args = array('s' => 'Example search term', 'cat' => 100, 'posts_per_page' => -1); 
$query = new WP_Query($args); 

if ($query->have_posts()) { 
    while ($query->have_posts()) { $query->the_post(); 
     foreach((get_the_category()) as $category) { 
      echo $category->cat_name . '<br />'; 
     } 
    } 
} 
wp_reset_query(); 

假設與編號100的類別是幾個小類一個父類,這個循環順利返回重複類別名稱列表。

我怎麼能只列出獨特類別的名稱和數量呢?並將兩個值都放入適當的變量中。

連同所有找到的結果的完整列表和它們的數量,也...

當然,我會盡力找出自己的解決方案,同時等待你這樣回答,因爲始終。但是,實際上,有一點幫助是值得讚賞的。

+1

你可以'你想在陣列上array_unique'它獨一無二。 http://php.net/manual/en/function.array-unique.php – Perumal

+0

@ Perumal93,謝謝你的線索,而不是現成的答案。我已經檢查過PHP手冊,現在有我自己完成的解決方案。 – YKKY

+0

不客氣。 – Perumal

回答

0

所以,我會迴應自己。再次)

感謝@ Perumal93的暗示指導我正確的方式,我現在有解決方案。

在情況下,它會是像我這樣的人使用,這裏是註釋掉的代碼準備複製和粘貼:

$args = array('s' => 'Example search term', 'cat' => 100, 'posts_per_page' => -1); 
$query = new WP_Query($args); 

if ($query->have_posts()) { 
$categories = array(); // 1. Defining the empty array outside of the loop 
    while ($query->have_posts()) { $query->the_post(); 
     foreach((get_the_category()) as $category) { 
      $categories[] = $category->cat_name; // 2. Filling the array with required data 
     } 
    } 
$u_categories = array_unique($categories); // 3. Clearing the array from repeated data 
$u_categories_cnt = count($u_categories); // 4. Counting the cleared array items 

foreach($u_categories as $category) {         // 5. Outputting 
    if($category == end($u_categories)) { echo $category.'.'; }   // the cleared 
    elseif($category == prev($u_categories)) { echo $category.' and '; } // array in a 
    else {echo $category.', '; }           // human 
}                  // friendly way 

echo $u_categories_cnt; // 6. Outputting the cleared array items count 
} 
wp_reset_query(); 

就是這樣