我使用以下函数按标题获取自定义帖子排序
$posts = get_posts(
array(
"orderby"=> "title",
"order" => "ASC",
"post_type" => "my-custom-post-type",
"posts_per_page" => -1,
"fields" => "ids",
"meta_query" => array(
array(
"key" => "ams_park_id",
"value" => get_the_ID(),
)
)
)
);
而且它是按标题排序的,问题是我有一篇帖子的标题是:“这是一个小世界”,这篇文章是在列表的开头排序的。
当前返回列表示例:
0 - "It\'s a small world"
1 - Albatross
2 - Alligator
3 - Baboon
4 - Camel
5 - Fox
6 - Hino
7 - Iguana
8 - Jackal
9...
如何使选择器忽略报价并将其发送到订单的“i”部分?示例:
0 - Albatross
1 - Alligator
2 - Baboon
3 - Camel
4 - Fox
5 - Hino
6 - Iguana
7 - "It\'s a small world"
8 - Jackal
9...
最合适的回答,由SO网友:RiddleMeThis 整理而成
试试这个。。。
$posts = get_posts(
array(
"orderby"=> "slug",
"order" => "ASC",
"post_type" => "my-custom-post-type",
"posts_per_page" => -1,
"fields" => "ids",
"meta_query" => array(
array(
"key" => "ams_park_id",
"value" => get_the_ID(),
)
)
)
);
注意到我变了
"orderby"=> "title",
到
"orderby"=> "slug"
. 通常,slug将接近标题,但所有特殊字符都将被删除。
SO网友:cjbj
只要你确定slug与标题真正对应,那么用slug代替title排序的答案就可以了。否则检索更安全$posts
从数据库中取消排序并使用PHP
\'suasort
用于自定义排序的命令。像这样:
function wpse359127_custom_sort ($post_a,$post_b) {
// Pick the component of the post object you want to use for comparison
$title_a = $post_a->post_title;
$title_b = $post_b->post_title;
// Remove any character that isn\'t A-Z, a-z or 0-9.
// Or maybe do more complex things if you language has ö\'s, for instance
$title_a = preg_replace("/[^A-Za-z0-9]/", \'\', $title_a);
$title_b = preg_replace("/[^A-Za-z0-9]/", \'\', $title_b);
// Return -1 of 1 depending on which post needs to be in front of the queue
if ($title_a < $title_b) return -1; else return 1;
}
uasort ($posts, \'wpse359127_custom_sort\');
注意:我没有测试这段代码,所以它可能有bug。