Skip to content

Instantly share code, notes, and snippets.

@serguk89
Forked from tybruffy/get_meta_values.php
Created October 28, 2018 17:33
Show Gist options
  • Save serguk89/4322f9e4811f31a99a498b120089ebf8 to your computer and use it in GitHub Desktop.
Save serguk89/4322f9e4811f31a99a498b120089ebf8 to your computer and use it in GitHub Desktop.
Get all distinct values of a meta field in Wordpress
function _get_all_meta_values($key) {
global $wpdb;
$result = $wpdb->get_col(
$wpdb->prepare( "
SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = 'publish'
ORDER BY pm.meta_value",
$key
)
);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment