Skip to content

Instantly share code, notes, and snippets.

@cyberwani
Created March 12, 2014 07:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cyberwani/9502441 to your computer and use it in GitHub Desktop.
Save cyberwani/9502441 to your computer and use it in GitHub Desktop.
Modify WordPress Query query
<?php
// With dual parameters
function modify_query_one( $clauses, $query ) {
global $wpdb;
if ( isset( $query->query['orderby'] ) && 'color' == $query->query['orderby'] ) {
$clauses['join'] .= <<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id)
LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
SQL;
$clauses['where'] .= " AND (taxonomy = 'color' OR taxonomy IS NULL)";
$clauses['groupby'] = "object_id";
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
$clauses['orderby'] .= ( 'ASC' == strtoupper( $query->get('order') ) ) ? 'ASC' : 'DESC';
}
return $clauses;
}
add_filter( 'posts_clauses', 'modify_query_one', 10, 2 );
// With single parameters
function modify_query_two( $pieces )
{
global $wpdb;
if( !is_user_logged_in() )
// Either
$pieces['where'] = str_replace(
"post_status = 'publish')",
"post_status = 'publish' OR $wpdb->posts.post_status = 'private') ",
$pieces['where']
);
// Or
$where_old = $pieces['where'];
$where_new = $where_old." HAVING distance < $this->distance";
$pieces['where'] = $where_new;
return $pieces;
}
add_filter( 'posts_clauses', 'modify_query_two' );
// Print query output
function intercept_query_clauses( $pieces )
{
echo '<style>#post-clauses-dump { display: block; background-color: #777; color: #fff; white-space: pre-line; }</style>';
// >>>> Inspect & Debug the Query
// NEVER EVER show this to anyone other than an admin user - unless you're in your local installation
if ( current_user_can( 'manage_options' ) )
{
$dump = var_export( $pieces, true );
// echo "<PRE id='post-clauses-dump'>{$dump}</PRE>";
echo '<pre id="post-clauses-dump">';
print_r($pieces);
echo '</pre>';
}
return $pieces;
}
add_filter( 'posts_clauses', 'intercept_query_clauses', 20, 1 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment