您只需添加DISTINCT
到您的SQL查询,类似于:
$cities = $wpdb->get_col("SELECT DISTINCT(meta_value) FROM $wpdb->usermeta WHERE meta_key = \'my_cities_meta_key\'" );
或者,如果出于某种原因希望使用php执行此操作(如果希望知道一个城市在只显示唯一条目之前会列出两次)
$cities = $wpdb->get_col("SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = \'my_cities_meta_key\'" );
$cities = array_keys(array_flip($cities));
如果您只想使用SQL根据用户角色进行筛选,类似的方法应该可以实现,但有点不太成熟,因为WP将用户角色存储在序列化数组中:
$cities = $wpdb->get_col("SELECT Distinct(c.meta_value)
FROM $wpdb->usermeta AS r
INNER JOIN $wpdb->usermeta AS c
ON r.user_id = c.user_id
WHERE r.meta_value LIKE \'%subscriber%\'
AND c.meta_key = \'my_cities_meta_key\'");
要添加基于多个元键的过滤器,需要执行更多操作
INNER JOIN
, e、 g.对于您的区域元键:
$cities = $wpdb->get_col("SELECT Distinct(c.meta_value)
FROM $wpdb->usermeta AS r
INNER JOIN $wpdb->usermeta AS c
ON r.user_id = c.user_id
INNER JOIN $wpdb->usermeta AS re
ON r.user_id = re.user_id
WHERE r.meta_value LIKE \'%subscriber%\'
AND c.meta_key = \'my_cities_meta_key\'
AND re.meta_key = \'region\'");