如何在 WordPress 中按字母顺序重新排序 get_post_types() 结果?

How to I reorder get_post_types() results alphabetically in WordPress?

我可以使用以下代码输出自定义 post 类型的列表。如何按字母顺序排列结果?

$args = array(
'public'   => true,
'_builtin' => false,
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types( $args, $output, $operator ); 
foreach ( $post_types  as $post_type ) {
$pts = get_post_type_object( $post_type );
$post_title = $pts->labels->name;
echo '<li><a href="' . get_post_type_archive_link( $post_type ) . '">' . $post_title . '</a></li>';
}
?>

最简单的方法是使用 PHP 对返回数组的值进行排序,而不是从 WordPress 本身请求排序列表。

$args = array(
'public'   => true,
'_builtin' => false,
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types( $args, $output, $operator );
asort( $post_types ); // the array is passed by reference, not assignment
// then loop your [now sorted] results

asort函数将维护密钥关联。如果您希望它重新索引数组,请改用 sort