Skip to content

Instantly share code, notes, and snippets.

@kaskad88
Last active January 22, 2020 09:04
Show Gist options
  • Save kaskad88/697b62b932f6120a53d42ef5458ddde3 to your computer and use it in GitHub Desktop.
Save kaskad88/697b62b932f6120a53d42ef5458ddde3 to your computer and use it in GitHub Desktop.
function cf_search_join( $join ) {
if ( is_admin() || ! is_search() ) {
return $join;
}
global $wpdb;
$join .= " LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id ";
return $join;
}
add_filter( 'posts_join', 'cf_search_join' );
function cf_search_where( $where ) {
if ( is_admin() || ! is_search() ) {
return $where;
}
global $wpdb;
$cf_where = '';
$cf_keys = array( '_sku' );
$or_op = '';
foreach ( $cf_keys as $cf_key ) {
$cf_where .= "{$or_op}({$wpdb->postmeta}.meta_key = '{$cf_key}' AND {$wpdb->postmeta}.meta_value LIKE $1)";
$or_op = ' OR ';
}
$where = preg_replace(
"/\(\s*{$wpdb->posts}.post_content\s+LIKE\s*(\'[^\']+\')\s*\)/",
"({$wpdb->posts}.post_content LIKE $1) OR {$cf_where}", $where );
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
function cf_search_distinct( $distinct ) {
if ( ! is_admin() && is_search() ) {
return 'DISTINCT';
}
return $distinct;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment