我创建了一个作者分类法。每个作者在姓名字段中都有姓名。稍后在分类页面上,列表按字母顺序显示。
<?php
$taxonomy = 'autorzy'; // <== Here define your custom taxonomy
$sorted = array(); // Initializing
// Get all terms alphabetically sorted
$terms = get_terms( array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'orderby' => 'name'
) );
// Loop through the array of WP_Term Objects
foreach( $terms as $term ) {
$term_name = $term->name;
$image = get_field('obrazek_wyrozniajacy', $term);
$term_link = get_term_link( $term, $taxonomy );
$first_letter = strtoupper($term_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>';
}
?>
问题是作者按名字排序,我希望按姓氏排序。我需要改进什么?
您无法轻松地以有效的方式对部分字符串进行排序,因此我建议在保存帖子时将
firstName
和 lastName
分开,并将它们分别存储在自己的元数据字段中:
// Breaks the fullname into first and last on-save and adds as metadata
add_action( 'created_autorzy', 'save_autorzy_meta', 10, 2 );
function save_autorzy_meta( $term_id, $tt_id ){
$taxonomy = 'autorzy';
$term = get_term($term_id, $taxonomy);
if ( isset($term['name']) ){
$name = explode(" ", $term['name']);
$firstName = $name[0] ?? "";
$lastName = $name[1] ?? "";
update_term_meta( $term_id, 'firstName', $firstName );
update_term_meta( $term_id, 'lastName', $lastName );
}
}
// Add a query for our taxonomy with a custom metaquery
$result = new WP_Query( array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
),
),
'meta_query' => array(
'relation' => 'AND',
'last_names' => array(
'key' => 'lastName',
'compare' => 'EXISTS',
),
'first_names' => array(
'key' => 'firstName',
'compare' => 'EXISTS',
),
),
'orderby' => 'meta_value_num',
'meta_key' => 'lastName',
'order' => 'ASC',
) );
文档:
created_{$taxonomy}
- https://developer.wordpress.org/reference/hooks/created_taxonomy/
update_term_meta()
- https://developer.wordpress.org/reference/functions/update_term_meta/
taxonomy query params
- https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters
orderby with meta_value_num
- https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters