Get custom field values in alphabetical order

2019-08-06 13:28发布

问题:

The function below lists the values ​​of a custom field in the order they are posted. example:

  • Frank Capra
  • Alfred Hitchcock
  • Woody Allen
  • Woody Allen
  • Frank Capra
  • Pedro Almodóvar

I'd like to get this list in alphabetical order and without repetition, with a link to each item <a href="Woody-Allen">Woody Allen</a>. example:

  • Alfred Hitchcock
  • Frank Capra
  • Pedro Almodóvar
  • Woody Allen

This is the code:

<?php
$movie_reviews = get_posts( 'numberposts=-1&orderby=post_name' );
foreach( $movie_reviews as $post ) : setup_postdata( $post );
?>
<span>
<?php $director = get_post_meta( $post->ID, "director", $single = true );
if( $director !== '' ) {
echo $director;
} ?>
</span>
<?php endforeach; ?>

Is this possible?

回答1:

Using get_posts, you can order posts with meta_value like this :

$movie_reviews = get_posts(array(
  'numberposts'=>-1,
  'order'=>'ASC',
  'orderby'=>'meta_value',
  'meta_key'=>'director'
));

To remove duplicates, you can build an array of directors :

$directors = array();
foreach( $movie_reviews as $post ) {
    $director = get_post_meta( $post->ID, 'director', true );
}
$directors = array_unique($directors);

And after you can display them as you want :

foreach ($directors as $director) {
    // display what you want
}

EDIT : To display only a* directors :

foreach ($directors as $director) {
    if (strtolower($director[0])=='a') {
        // display what you want
    }
}