Skip to content

Instantly share code, notes, and snippets.

@nigelheap
Created March 20, 2017 22:33
Show Gist options
  • Save nigelheap/84533193de7a01428d00d74d7b6d7f4a to your computer and use it in GitHub Desktop.
Save nigelheap/84533193de7a01428d00d74d7b6d7f4a to your computer and use it in GitHub Desktop.
Wordpress: Returns an array of all meta values over all posts of a certain type based on a key, can be unique or not
<?php
/**
* Returns an array of all meta values over all posts of a certain type based on a key, can be unique or not
*/
function nigelheap_get_meta_values($key = '', $type = 'post', $status = 'publish', $unique = true) {
global $wpdb;
if( empty( $key ) )
return;
$distinct = '';
if($unique){
$distinct = 'DISTINCT';
}
$r = $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 = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
return $r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment