Search code examples
phparrayswordpresscustom-post-typearray-unique

Wordpress Get unique custom field values in a list


I have a whole list of directors but would like to display only their unique names not duplicates. Something that looks like

director A, Director B, Director C,...

NOT

director A, Director A, Director B, Director C, Director C,...

I try to do this with array_unique but it doesn't seem to put any data in the arrays.

I see that the foreach loop displays all the names of the directors but somehow the array $alldirectors stays empty.

Here is the code I'm using.

<?php
$resume = get_posts(array(
          'post_type' =>'resume', 
          'numberposts'=>-1, 
          'meta_key' => 'director', 
          'meta_value' => '' 
));

$alldirectors = array();
foreach( $resume as $post ) {
      $director = get_post_meta( $post->ID, 'director', true );
 }

 $directors = array_unique($alldirectors);
 foreach ($directors as $director) {
  echo $directors;
 }
 ?>

It's probably something simple that I'm missing but I'm new to php and wordpress Thanks for all your help.


Solution

  • You are not storing the directors name in $alldirectors therefore it is empty try this one

    $alldirectors = array();
    foreach( $resume as $post ) {
        $alldirectors[]=   get_post_meta( $post->ID, 'director', true );
     }
    

    And then use your loop

     $directors = array_unique($alldirectors);
     foreach ($directors as $director) {
      echo $directors;
     }