Created
June 27, 2014 22:52
-
-
Save iamcanadian1973/aefea2c22c6b31bd4848 to your computer and use it in GitHub Desktop.
Retrieve all post meta for a given $key by $post_type. This function is useful if you need to do any front-end sorting of posts by meta key/values and need to populate a select
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Retreive all post meta for a given $key by $post_type | |
* | |
* This function is useful if you need to do any frontend sorting of posts by meta key/values and need to populate a select | |
* | |
* @param string | |
* @param string | |
* @param string | |
* @param bool | |
* @return array | |
*/ | |
function get_meta_values( $key = '', $post_type = 'post', $status = 'publish', $remove_duplicates = TRUE ) { | |
global $wpdb; | |
if( empty( $key ) ) | |
return; | |
$r = $wpdb->get_col( $wpdb->prepare( " | |
SELECT 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, $post_type ) ); | |
if( $remove_duplicates ) | |
return array_unique( $r ); | |
return $r; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment