Skip to content

Instantly share code, notes, and snippets.

@jackgregory
Last active February 16, 2017 11:45
Show Gist options
  • Save jackgregory/a9f30668c022e8530185 to your computer and use it in GitHub Desktop.
Save jackgregory/a9f30668c022e8530185 to your computer and use it in GitHub Desktop.
WooCommerce Search by SKU
add_filter( 'posts_where', 'search_by_sku' );
function search_by_sku( $where ) {
if( ! is_search() ) {
return $where;
}
global $wpdb;
$query = get_search_query();
$query = $wpdb->esc_like( $query );
$where .=" OR {$wpdb->posts}.ID IN (SELECT IF({$wpdb->posts}.post_parent>0,{$wpdb->posts}.post_parent,{$wpdb->posts}.ID) FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->postmeta}.meta_key = '_sku' AND {$wpdb->postmeta}.meta_value LIKE '%$query%' AND {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id)";
return $where;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment