Created
November 15, 2018 06:59
-
-
Save punit5658/793776feb29ae6457cf6ababc419ef87 to your computer and use it in GitHub Desktop.
Enable SKU search in woocommerce
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 | |
/** | |
* Join posts and postmeta tables | |
* | |
* @param string $join | |
* @param WP_Query $query | |
* | |
* @see https://iconicwp.com/blog/add-product-sku-woocommerce-search/ | |
* | |
* @return string | |
*/ | |
function iconic_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} iconic_post_meta ON {$wpdb->posts}.ID = iconic_post_meta.post_id "; | |
return $join; | |
} | |
add_filter( 'posts_join', 'iconic_product_search_join', 10, 2 ); | |
/** | |
* Modify the search query with posts_where. | |
* | |
* @param string $where | |
* @param WP_Query $query | |
* | |
* @see https://iconicwp.com/blog/add-product-sku-woocommerce-search/ | |
* | |
* @return string | |
*/ | |
function iconic_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 (iconic_post_meta.meta_key = '_sku' AND iconic_post_meta.meta_value LIKE $1)", $where ); | |
return $where; | |
} | |
add_filter( 'posts_where', 'iconic_product_search_where', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment