Skip to content

Instantly share code, notes, and snippets.

@yousufansa
Created April 15, 2019 05:42
Show Gist options
  • Save yousufansa/d8c09db8782935bb9a429e617967d8e0 to your computer and use it in GitHub Desktop.
Save yousufansa/d8c09db8782935bb9a429e617967d8e0 to your computer and use it in GitHub Desktop.
WC - Add SKU In WooCommerce Product Search
/**
* Join posts and postmeta tables
*
* @param string $join
* @param WP_Query $query
* @return string
*/
if( ! function_exists( 'wc_custom_product_search_join' ) ) {
function wc_custom_product_search_join( $join, $query ) {
if ( ! $query->is_main_query() || is_admin() || ! is_search() || ! is_woocommerce() ) {
return $join;
}
global $wpdb;
$join .= " LEFT JOIN {$wpdb->postmeta} postmeta ON {$wpdb->posts}.ID = postmeta.post_id ";
return $join;
}
}
add_filter( 'posts_join', 'wc_custom_product_search_join', 10, 2 );
/**
* Modify the search query with posts_where.
*
* @param string $where
* @param WP_Query $query
* @return string
*/
if( ! function_exists( 'wc_custom_product_search_where' ) ) {
function wc_custom_product_search_where( $where, $query ) {
if ( ! $query->is_main_query() || is_admin() || ! 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 (postmeta.meta_key = '_sku' AND postmeta.meta_value LIKE $1)", $where );
return $where;
}
}
add_filter( 'posts_where', 'wc_custom_product_search_where', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment