Skip to content

Instantly share code, notes, and snippets.

@erikyo
Created June 25, 2021 10:17
Show Gist options
  • Select an option

  • Save erikyo/1816a48f8daccb5da4a9743ea2b3d760 to your computer and use it in GitHub Desktop.

Select an option

Save erikyo/1816a48f8daccb5da4a9743ea2b3d760 to your computer and use it in GitHub Desktop.
Adds products found by sku and gtin to wp search query (WooCommerce)
<?php
/**
* Returns an array of product ids similar to the given sku / gtin
* @param $sku - the search key
* @param int $limit - maximum number of returned items
*
* @return array|bool
*/
function prefix_get_product_arr_by_sku( $sku, $limit = 10 ) {
global $wpdb;
$products_id = $wpdb->get_results( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE ( meta_key = '_sku' OR meta_key = '_gtin') AND meta_value LIKE '%s' LIMIT {$limit}", '%'.$sku.'%' ) );
if ( $products_id ) {
foreach ($products_id as $product_id) $products[$product_id->post_id] = $product_id->post_id;
}
return !empty($products) ? array_unique($products) : false;
}
function prefix_search_inject_sku_gtin( $search, $query ) {
global $wpdb;
if(isset($query->query['s']) && !empty($query->query['s'])){
$products = prefix_get_product_arr_by_sku($query->query['s']);
if( !empty( $products ) ) {
$search = str_replace( 'AND (((', " AND ((({$wpdb->posts}.ID IN (" . implode( ',', $products ) . ")) OR (", $search);
}
}
return $search;
}
add_filter( 'posts_search', 'prefix_search_inject_sku_gtin', 999, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment