2 回答

TA貢獻1772條經驗 獲得超5個贊
對術語進行排序不會對您想要做的事情產生影響。如果您想包含結果中沒有的字母,那么無論結果如何排序,您都不能將結果用于循環,因為它只能循環遍歷其中的內容。
相反,我們可以簡單地循環字母表并使用字母作為鍵來從數組中獲取術語。
首先,循環遍歷字母表以顯示 div 中的字母tag-wrap:
$alphabet = range('A', 'Z'); // 1. use range to get the alphabet
<div class="tag-wrap">
<ul>
<?php
// 2. display the regular alphabet instead of the letters from your results
foreach ( $alphabet as $letter ) : ?>
<li class="border-radius">
<a href="#<?php echo $letter; ?>"><h3><?php echo $letter; ?></h3></a>
</li>
<?php endforeach; ?>
</ul>
</div>
現在我們將再次循環遍歷字母表,這次$term_list使用字母作為鍵來獲取結果。如果沒有術語,那么您可以顯示一條消息,否則您可以像以前一樣顯示列表。
<div class="tag-list">
<?php
// 3. display the results by looping through the alphabet to ensure all letters are included
foreach ( $alphabet as $letter) : ?>
<div class="term-row" id="<?php echo $letter; ?>">
<div class="term-letter">
<h3><?php echo $letter; ?></h3>
</div>
<div class="tag-items">
<?php
// 4. Get the terms for this letter, if there are none show a message
$termsforletter = $term_list[$letter];
if (empty($terms for letter)) { ?>
<p>No Results for this letter</p>
<?php }
else {
foreach ( $termsforletter as $term ): ?>
<div class="tag-item">
<a href="<?php echo get_term_link( $termsforletter );?>"><?php echo $term->name;?></a>
</div>
<?php endforeach;
} ?>
</div>
</div>
<?php endforeach;?>
</div>
(注意:此代碼未經測試,但總體思路已經存在)
這也意味著您不必擔心對數組進行任何排序,因為我們使用字母循環對顯示/進行排序

TA貢獻1779條經驗 獲得超6個贊
這是基于 FluffyKitten 答案的工作,只是更改了檢查以在沒有字母術語的情況下顯示文本。
<?php
$alphabet = range('A', 'Z');
$args = array(
'taxonomy' => 'post_tag',
'hide_empty' => false,
'order' => 'DESC',
'orderby' => 'slug'
);
$terms = get_terms($args);
$term_list = [];
foreach ( $terms as $term ){
$first_letter = strtoupper($term->name[0]);
$term_list[$first_letter][] = $term;
}
unset($term); ?>
<div class="tag-wrap">
<ul>
<?php foreach ( $alphabet as $letter ) : ?>
<li>
<a href="#<?php echo $letter; ?>"><h3><?php echo $letter; ?></h3></a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="tag-list">
<?php
foreach ( $alphabet as $letter) : ?>
<div class="term-row" id="<?php echo $letter; ?>">
<div class="term-letter">
<h3><?php echo $letter;?></h3>
</div>
<div class="tag-items">
<?php
$termsforletter = $term_list[$letter];
if (empty($termsforletter )): ?>
<div class="tag-item">
<p>No topics matching this letter </p>
</div>
<?php else:
foreach ( $termsforletter as $term ): ?>
<div class="tag-item">
<a href="<?php echo get_term_link( $term ); ?>"><?php echo $term->name; ?></a>
</div>
<?php endforeach;?>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
- 2 回答
- 0 關注
- 164 瀏覽
添加回答
舉報