Wordpress在列表中获取唯一的自定义字段值

Phi*_*hil 1 php arrays wordpress array-unique custom-post-type

我有一个完整的董事名单,但只想显示其唯一的名字,不要重复。看起来像

导演A,导演B,导演C ...

导演A,导演A,导演B,导演C,导演C,...

我尝试使用array_unique做到这一点,但似乎没有在数组中放入任何数据。

我看到foreach循环显示了所有Director的名称,但是数组$ alldirectors却保持为空。

这是我正在使用的代码。

<?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;
 }
 ?>
Run Code Online (Sandbox Code Playgroud)

我可能想念的很简单,但是我是php和wordpress的新手。感谢您的所有帮助。

Sum*_*mit 6

尝试像这样使用标准查询

global $wpdb; (this is required when are you inside the function)

$values = $wpdb->get_results("SELECT DISTINCT meta_value FROM $wpdb->postmeta pm, $wpdb->post p WHERE meta_key  = 'director' and pm.post_id=p.ID  and p.post_type='resume' ",ARRAY_A);

print_r($values);
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答。不过我要纠正一点:“$wpdb-&gt;post”应该是“$wpdb-&gt;posts”。 (2认同)
  • 注意:当 WordPress 查询 `get_posts` 时,它会抓取元数据并将其放入内存中,因此不应存在带有 `get_post_meta` 的单独数据库请求。 (2认同)