我有一个针对员工的自定义帖子类型,它使用帖子标题作为人员姓名。为了按姓氏排序,我使用顺序过滤器查找标题中的最后一个单词,然后按它排序:
function posts_orderby_lastname ($orderby_statement)
{
$orderby_statement = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) ASC";
return $orderby_statement;
}
这对于大多数具有正常名字和姓氏的员工来说非常有用,但我不知道如何为类似的名字(所有都应该按“条款”排序:
)圣诞老人
圣诞老人三世
小圣诞老人
圣诞老人克林格尔
M。圣诞老人先生
我假设我可以有一个存储的数组,然后检查这些术语(如“Jr.”、“II”等)或检查找到的术语的长度是否大于 3,但我不知道如何将其实现到代码中。任何想法或帮助将不胜感激 - 提前致谢!
我遇到了类似的问题,这就是我解决的方法。您可以针对您描述的所有边缘情况扩展 if 语句。
$args = array(
'post_type' => 'page',
'orderby' => 'menu_order',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'order' => 'ASC'
);
$posts = get_posts( $args );
// Order by second word in title, deal with edge cases
$lastname = array();
foreach( $posts as $key => $post ) {
$word = explode( ' ', $post->post_title );
$name = null;
if( strlen($word[1]) == 1 ) {
// Second word only 1 letter, so use third word if set
$name = $word[2];
} elseif( $word[3] == 'Sr.' ) {
// Third word is 'Sr.', so use 2nd word
$name = $word[1];
} else {
$name = $word[1];
}
$lastname[$key] = $name;
}
array_multisort( $lastname, SORT_ASC, $posts );
// Loop through posts
foreach( $posts as $post ) {
echo $post->post_title;
}
我稍微修改了一下以满足我的需要,因为我的名字就像
黎明 A.阿德尔森
蒂莫西·史密斯
小约翰·A·史密斯
$args = array(
'post_type' => 'YOUR_POST_TYPE',
'posts_per_page' => -1,
'order' => 'ASC'
);
$posts = get_posts( $args );
// Order by second word in title, deal with edge cases
$lastname = array();
foreach( $posts as $key => $post ) {
$word = explode( ' ', $post->post_title );
$name = null;
if( strlen($word[1]) == 2 ) {
// Second word 1 letter and dot, so use third word if set
$name = $word[2];
} elseif( $word[3] == 'Jr.' ) {
// Third word is 'Jr.', so use 2nd word
$name = $word[2];
} else {
$name = $word[1];
}
$lastname[$key] = $name;
}
array_multisort( $lastname, SORT_ASC, $posts );
// Loop through posts
foreach( $posts as $post ) {
?>
<div>
<?php echo $post->post_title; ?>
</div>
<?php
}
?>
</div>
这是一种更好的方法,至少其他方法对我来说根本不起作用。 这将删除第一个空格之前的所有内容,并对字符串的其余部分应用标准排序。请务必根据您的实际需要修改
is_main_query()
和 is_category()
。
function posts_orderby_lastname( $orderby_statement )
{
if( is_main_query() && is_category() ) {
return "SUBSTRING_INDEX(post_title, ' ', -1)";
} else {
return $orderby_statement;
}
}