这里的技巧是用分类法的术语创建一个数组并对其进行排序。在进行排序之前,我们需要划分全名“;约翰·多伊;“分隔字符串”;“约翰”;和;能源部;。然后我们可以按姓氏对姓名进行排序。
其余的说明和文档都在代码中。
这应该是可行的,但我还没有用实际的WP术语对此进行测试,所以请先进行测试。
<?php // Get the taxonomy\'s terms
$terms = get_terms(
array(
\'taxonomy\' => \'supporter\',
\'hide_empty\' => false,
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Create a new empty array of supporters ( $supporters ) which will include first and last names.
$supporters = [];
foreach ( $terms as $term ) {
// Divide the whole name to different words.
// First word ( name_divided[0] ) will be the person\'s first name
// Second word ( name_divided[1] ) will be the person\'s last name
$name_divided = explode( \' \', trim($term->name) );
// We\'ll create an array $supporters which has the following structure:
// $supporters[0] = array (
// \'firstname\' => \'John\',
// \'lastname\' => \'Doe\' ),
// )
$supporters[] = array( \'firstname\' => $name_divided[0], \'lastname\' => $name_divided[1] );
}
// Here\'s the magic. Sort the array by last name
array_multisort (array_column($supporters, \'lastname\'), SORT_ASC, $supporters);
// Run a loop and print them all
foreach ( $supporters as $supporter ) { ?>
<li class="supporter-name"><?php echo $supporter[\'lastname\'] . \', \' . $supporter[\'firstname\']; ?></li>
<?php
}
} ?>
Edit: If the name list consists of names that has 3 or more names, ie. "John of England".
更换节段
$supporters[] = array( \'firstname\' => $name_divided[0], \'lastname\' => $name_divided[1] );
代码如下:
//Get all other names than last name
$firstnames = \'\';
for ($x = 0; $x < (count($name_divided) - 1); $x++ ) {
$firstnames .= $name_divided[$x];
// If this is not the last one of first names, add space between names
if ( $x != (count($name_divided) - 2) )
$firstnames .= \' \';
}
// Use last word (key in array) as last name
$lastname = array_pop($name_divided);
$supporters[] = array( \'firstname\' => $firstnames, \'lastname\' => $lastname );
此修改与之前的代码相结合,将输出;英国的约翰“;像
英国约翰