I use this code to list unique values of custom field name "authors" from all posts. It works just fine, but I would like to limit results, to get values which appear in at least for example 20 posts? How to drop out custom field values which are in use in less than 20 posts?

global $wpdb;

$query = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'authors' ORDER BY meta_value;";
$authors = $wpdb->get_results( $query );

foreach( $authors as $author ) :
echo'<li>'; echo $author->meta_value; echo '</li>';

1 Answer 1


From what I understand I think you can try something like:

SELECT meta_value, COUNT(post_id) as count FROM $wpdb->postmeta WHERE meta_key = 'authors' GROUP BY meta_value HAVING count >= 20 ORDER BY meta_value;

Let me know if this works for you!

  • Hello @jonathanbardo Is there chance to sort results in some order, for example per count, most used first? Aug 2, 2015 at 12:02
  • You could simply do an 'ORDER BY count' if you want to instead of the 'ORDER BY meta_value. Aug 3, 2015 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.