iamcanadian1973
6/27/2014 - 10:52 PM

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/

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

/**
 * 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;
}