Created
May 2, 2013 13:56
-
-
Save sbruner/5502361 to your computer and use it in GitHub Desktop.
Piklist: updated get_meta_sql
This file contains hidden or 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
public function get_meta_sql($meta_query, $queries, $type, $primary_table, $primary_id_column, $context) | |
{ | |
if (in_array($type, array('user'))) | |
{ | |
return $meta_query; | |
} | |
global $wpdb; | |
$where = array_filter(preg_split('/$\R?^/m', trim(substr($meta_query['where'], 6, strlen($meta_query['where']) - 8)))); | |
if (!empty($where)) | |
{ | |
$relation = 'AND'; | |
$meta_table = substr($primary_table, 0, strlen($primary_table) - 1) . 'meta'; | |
$meta_prefixes = array($meta_table . '.'); | |
for ($i = 1; $i < count($where); $i++) | |
{ | |
array_push($meta_prefixes, 'mt' . $i . '.'); | |
} | |
for ($i = 0; $i < count($where); $i++) | |
{ | |
if ($i > 0) | |
{ | |
if ($i == 1) | |
{ | |
$relation = trim(substr($where[$i], 0, strpos($where[$i], '('))); | |
} | |
$where[$i] = substr($where[$i], strpos($where[$i], '(')); | |
} | |
$where[$i] = str_replace($meta_prefixes, '', $where[$i]); | |
} | |
$from = $meta_table; | |
$where[0] = str_replace(array("meta_key", "meta_value"), array("{$meta_table}.meta_key", "{$meta_table}.meta_value"), $where[0]); | |
for ($i = 1; $i < count($where); $i++) | |
{ | |
$from .= " INNER JOIN wp_postmeta AS mt{$i} ON {$meta_table}.{$type}_id = mt{$i}.{$type}_id"; | |
$where[$i] = str_replace(array("meta_key", "meta_value"), array("mt{$i}.meta_key", "mt{$i}.meta_value"), $where[$i]); | |
} | |
$query = "SELECT {$meta_table}.{$type}_id FROM {$from} WHERE (" . implode(' ' . $relation . ' ', $where) . ") GROUP BY {$meta_table}.{$type}_id"; | |
$post_ids = $wpdb->get_col($query); | |
if (!empty($post_ids)) | |
{ | |
$meta_query['join'] = ''; | |
$meta_query['where'] = " AND \n\t{$primary_table}.{$primary_id_column} IN (\n\t\t" . implode("\n\t\t,", $post_ids) . "\n\t) \n"; | |
} | |
} | |
return $meta_query; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment