Skip to content

Instantly share code, notes, and snippets.

@TamiasSibiricus
Created February 13, 2017 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TamiasSibiricus/917b3dfc2b13b97e644ea739a1a1a306 to your computer and use it in GitHub Desktop.
Save TamiasSibiricus/917b3dfc2b13b97e644ea739a1a1a306 to your computer and use it in GitHub Desktop.
<?php
class WP_Meta_Query {
//...
protected function get_sql_for_query( &$query, $depth = 0 ) {
$sql_chunks = array(
'join' => array(),
'where' => array(),
);
$sql = array(
'join' => '',
'where' => '',
);
$indent = '';
for ( $i = 0; $i < $depth; $i++ ) {
$indent .= " ";
}
foreach ( $query as $key => &$clause ) {
if ( 'relation' === $key ) {
$relation = $query['relation'];
} elseif ( is_array( $clause ) ) {
// This is a first-order clause.
if ( $this->is_first_order_clause( $clause ) ) {
$clause_sql = $this->get_sql_for_clause( $clause, $query, $key );
$where_count = count( $clause_sql['where'] );
if ( ! $where_count ) {
$sql_chunks['where'][] = $where = '';
} elseif ( 1 === $where_count ) {
//Patch: remember where condition
$sql_chunks['where'][] = $where =$clause_sql['where'][0];
} else {
//Patch: remember where condition
$where = implode( ' AND ', $clause_sql['where'] );
$sql_chunks['where'][] = '( ' . $where . ' )';
}
//Patch: add where conditions into join. Queries work faster 10 times
$clause_sql['join'][0] = str_replace(')', ' AND '.$where.')', $clause_sql['join'][0]);
$sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
// This is a subquery, so we recurse.
} else {
$clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
$sql_chunks['where'][] = $clause_sql['where'];
$sql_chunks['join'][] = $clause_sql['join'];
}
}
}
// Filter to remove empties.
$sql_chunks['join'] = array_filter( $sql_chunks['join'] );
$sql_chunks['where'] = array_filter( $sql_chunks['where'] );
if ( empty( $relation ) ) {
$relation = 'AND';
}
// Filter duplicate JOIN clauses and combine into a single string.
if ( ! empty( $sql_chunks['join'] ) ) {
$sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
}
// Generate a single WHERE clause with proper brackets and indentation.
if ( ! empty( $sql_chunks['where'] ) ) {
$sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
}
return $sql;
}
//....
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment