Skip to content

Instantly share code, notes, and snippets.

@seamusleahy
Created September 11, 2012 17:00
Show Gist options
  • Save seamusleahy/3699833 to your computer and use it in GitHub Desktop.
Save seamusleahy/3699833 to your computer and use it in GitHub Desktop.
A utility function for WordPress to retrieve metadata from post to display in a list or drop-down
<?php
/**
* Retrive the tuples of metadata in a given set of post-types.
*
* @param $metakeys string|array - The metakeys to be the tuple elements
* @param $post_types string|array optional - The post-types to limit the query on. Defaults to the current post-type
*
* <?php
* $cities = get_postmeta_tuples( array( 'city', 'state' ), 'chapters' );
* ?>
* <h3>Cities with Local Chapters</h3>
* <ul>
* <?php foreach( $cities as $city ): ?>
* <li><?php echo $city->city, ', ', $city->state; ?></li>
* <?php endforeach; ?>
* </ul>
*/
function get_postmeta_tuples( $metakeys, $post_types=null ) {
global $wpdb, $post;
// Prepare $post_type if not provided by caller
if( is_null($post_types) ) {
if( !empty($post->post_type) ) {
$post_types = array( $post->post_type );
} else {
return array(); // Return no results
}
}
$post_types = (array) $post_types;
$metakeys = (array) $metakeys;
// ensure we have metakeys to do the query on
if( count($metakeys)==0 ) {
return array(); // Return no results
}
// build the query
$select = "SELECT ";
$select_vals = array();
$from = "\nFROM {$wpdb->posts} as posts";
$join = "";
$where = "\nWHERE posts.post_status = 'publish' AND posts.post_type IN ";
$groupby = "\nGROUP BY ";
$groupby_vals = array();
foreach( $metakeys as $metakey ) {
$metakey = $wpdb->escape($metakey);
$select_vals[] = "{$metakey}meta.meta_value as {$metakey}";
$groupby_vals[] = $metakey;
$join .= "\nJOIN {$wpdb->postmeta} as {$metakey}meta on {$metakey}meta.post_id = posts.ID AND {$metakey}meta.meta_key = '{$metakey}'";
}
$select .= implode( ', ', $select_vals );
$groupby .= implode( ', ', $groupby_vals );
foreach( $post_types as $k => $post_type ) {
$post_type = $wpdb->escape( $post_type );
$post_types[$k] = $post_type;
}
$where .= "('".(implode("','", $post_types))."')";
return $wpdb->get_results( $select . $from . $join . $where . $groupby );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment