Search code examples
wordpresscustom-post-typealphabetical

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


I'm able to output a list of my custom post types using the code below. How can I order the results alphabetically?

$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>';
}
?>

Solution

  • The easiest way would be to use PHP to sort the values of the returned array, instead of requesting a sorted list from WordPress itself.

    $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
    

    The asort function will maintain the key association. If you want it to re-index the array, use sort instead.