0

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?

<ul>
<?
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>';
endforeach;
?>
</ul>
2

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? – Advanced SEO Aug 2 '15 at 12:02
  • You could simply do an 'ORDER BY count' if you want to instead of the 'ORDER BY meta_value. – jonathanbardo Aug 3 '15 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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