我创建了一个在页面上显示作者的分类法。我创建了一个额外的“姓氏”字段来按姓氏对作者进行排序。 作者根据姓氏的第一个字母分为几组。
<?php
$taxonomy = 'autorzy'; // <== Here define your custom taxonomy
// Get all terms alphabetically sorted
$terms = get_terms( array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'posts_per_page' => -1,
'orderby' => $term_last_name,
'order' => 'DESC',
) );
$sorted = array(); // Initializing
// Loop through the array of WP_Term Objects
foreach( $terms as $term ) {
$term_name = $term->name;
$term_last_name = get_field('nazwisko', $term);
$image = get_field('obrazek_wyrozniajacy', $term);
$term_link = get_term_link( $term, $taxonomy );
$first_letter = strtoupper($term_last_name[0]);
// Group terms by their first starting letter
if( ! empty($term_link) ) {
$sorted[$first_letter][] = '<li><a href="'.$term_link.'">' .'<img src="'.$image['url'].'" />'.$term_name.'</a></li>';
} else {
$sorted[$first_letter][] = '<li>'.$term_name.'</li>';
}
}
// Loop through grouped terms by letter to display them by letter
foreach( $sorted as $letter => $values ) {
echo '<div class="tax-by-letter" id="tax-letter-'.$letter.'">
<h3 class="tax-letter-'.$letter.'">'.$letter.'</h3>
<ul class="nav">' . implode('', $values) . '</ul>
</div>';
}
?>
问题是创建的组没有按字母顺序显示。 目前,列表显示为 Z、R、P、C,我希望它按照字母 A、B、C 来显示
您正在尝试
orderby
未定义的变量$term_last_name
。相反,您应该使用 'meta_key' => 'nazwisko'
包含元键本身,并指示 get_terms
按此键按字母顺序排序,使用 'orderby' => 'meta_value'
:
$taxonomy = 'autorzy';
$terms = get_terms( array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'posts_per_page' => -1,
'meta_key' => 'nazwisko',
'orderby' => 'meta_value',
'order' => 'DESC',
));