Created
November 17, 2016 17:41
-
-
Save Tmeister/619165665eaf63784deeb06976510eea to your computer and use it in GitHub Desktop.
Include the TCB saved meta into query search fields - BAD IDEA!!
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
<?php | |
/** | |
* include the TCB saved meta into query search fields | |
* | |
* wordpress actually allows inserting post META fields in the search query, | |
* but it will always build the clauses with AND (between post content and post meta) e.g.: | |
* WHERE (posts.title LIKE '%xx%' OR posts.post_content) AND (postsmeta.meta_key = 'tve_save_post' AND postsmeta.meta_value LIKE '%xx%') | |
* | |
* - we cannot use this, so we hook into the final pieces of the built SQL query - we need a solution like this: | |
* WHERE ( (posts.title LIKE '%xx%' OR posts.post_content OR (postsmeta.meta_key = 'tve_save_post' AND postsmeta.meta_value LIKE '%xx%') ) | |
* | |
* @param array $pieces | |
* @param WP_Query $wpQuery | |
* | |
* @return array | |
*/ | |
function tve_process_search_clauses( $pieces, $wpQuery ) { | |
if ( is_admin() || empty( $pieces ) || ! $wpQuery->is_search() ) { | |
return $pieces; | |
} | |
/** @var wpdb $wpdb */ | |
global $wpdb; | |
$query = ''; | |
$n = ! empty( $q['exact'] ) ? '' : '%'; | |
$q = $wpQuery->query_vars; | |
if ( ! empty( $q['search_terms'] ) ) { | |
foreach ( $q['search_terms'] as $term ) { | |
if ( method_exists( $wpdb, 'esc_like' ) ) { // WP4 | |
$term = $wpdb->esc_like( $term ); | |
} else { | |
$term = like_escape( $term ); // like escape is deprecated in WP4 | |
} | |
$like = $n . $term . $n; | |
$query .= "((tve_pm.meta_key = 'tve_save_post')"; | |
$query .= $wpdb->prepare( " AND (tve_pm.meta_value LIKE %s)) OR ", $like ); | |
} | |
} | |
if ( ! empty( $query ) ) { | |
// add to where clause | |
$pieces['where'] = str_replace( "((({$wpdb->posts}.post_title LIKE '{$n}", "( {$query} (({$wpdb->posts}.post_title LIKE '{$n}", $pieces['where'] ); | |
$pieces['join'] = $pieces['join'] . " LEFT JOIN {$wpdb->postmeta} AS tve_pm ON ({$wpdb->posts}.ID = tve_pm.post_id)"; | |
if ( empty( $pieces['groupby'] ) ) { | |
$pieces['groupby'] = "{$wpdb->posts}.ID"; | |
} | |
} | |
return ( $pieces ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment