2 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
對術(shù)語進(jìn)行排序不會對您想要做的事情產(chǎn)生影響。如果您想包含結(jié)果中沒有的字母,那么無論結(jié)果如何排序,您都不能將結(jié)果用于循環(huán),因?yàn)樗荒苎h(huán)遍歷其中的內(nèi)容。
相反,我們可以簡單地循環(huán)字母表并使用字母作為鍵來從數(shù)組中獲取術(shù)語。
首先,循環(huán)遍歷字母表以顯示 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>
現(xiàn)在我們將再次循環(huán)遍歷字母表,這次$term_list使用字母作為鍵來獲取結(jié)果。如果沒有術(shù)語,那么您可以顯示一條消息,否則您可以像以前一樣顯示列表。
<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>
(注意:此代碼未經(jīng)測試,但總體思路已經(jīng)存在)
這也意味著您不必?fù)?dān)心對數(shù)組進(jìn)行任何排序,因?yàn)槲覀兪褂米帜秆h(huán)對顯示/進(jìn)行排序

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是基于 FluffyKitten 答案的工作,只是更改了檢查以在沒有字母術(shù)語的情況下顯示文本。
<?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 關(guān)注
- 162 瀏覽
添加回答
舉報(bào)