Skip to content

Instantly share code, notes, and snippets.

@mmilosheski
Last active June 19, 2017 08:04
Show Gist options
  • Save mmilosheski/591deedb7c594bcdf2d1822e50ee78cf to your computer and use it in GitHub Desktop.
Save mmilosheski/591deedb7c594bcdf2d1822e50ee78cf to your computer and use it in GitHub Desktop.
/* paste this into your functions.php of the theme */
/ * Join posts and postmeta tables */
function product_search_join( $join ) {
if( ! is_search() || ! is_woocommerce() ) {
return $join;
}
global $wpdb;
$join .= " LEFT JOIN {$wpdb->postmeta} wp_post_meta ON {$wpdb->posts}.ID = wp_post_meta.post_id ";
return $join;
}
add_filter('posts_join', 'product_search_join' );
/* Modify the search query with posts_where*/
function product_search_where( $where ) {
if( ! is_search() || ! is_woocommerce() ) {
return $where;
}
global $wpdb;
$where = preg_replace(
"/\(\s*{$wpdb->posts}.post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"({$wpdb->posts}.post_title LIKE $1) OR (wp_post_meta.meta_key = '_sku' AND wp_post_meta.meta_value LIKE $1)", $where );
return $where;
}
add_filter( 'posts_where', 'product_search_where' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment