Skip to content

Instantly share code, notes, and snippets.

@kaskad88
Created January 28, 2020 07:51
Show Gist options
  • Save kaskad88/ded2e158e509638e28ba2aeb6b6ed510 to your computer and use it in GitHub Desktop.
Save kaskad88/ded2e158e509638e28ba2aeb6b6ed510 to your computer and use it in GitHub Desktop.
add_filter( 'the_posts', '__search_by_sku' );
function __search_by_sku( $posts ) {
if ( is_admin() || ! is_search() ) {
return $posts;
}
$ignoreIds = array( 0 );
foreach ( $posts as $post ) {
$ignoreIds[] = $post->ID;
}
$matchedSku = __get_parent_post_by_sku( get_search_query(), $ignoreIds );
if ( $matchedSku ) {
foreach ( $matchedSku as $product_id ) {
$posts[] = get_post( $product_id->post_id );
}
}
return $posts;
}
function __get_parent_post_by_sku( $sku, $ignoreIds ) {
global $wpdb, $wp_query;
$ignoreIdsForMySql = implode(",", $ignoreIds);
$variationsSql = "
SELECT p.post_parent as post_id FROM $wpdb->posts as p
join $wpdb->postmeta pm
on p.ID = pm.post_id
and pm.meta_key='_sku'
and pm.meta_value LIKE '%$sku%'
join $wpdb->postmeta visibility
on p.post_parent = visibility.post_id
and visibility.meta_key = '_visibility'
and visibility.meta_value <> 'hidden'
";
$variationsSql .= "
where 1
AND p.post_parent <> 0
and p.ID not in ($ignoreIdsForMySql)
and p.post_status = 'publish'
group by p.post_parent
";
$variations = $wpdb->get_results($variationsSql);
foreach ( $variations as $post ) {
$ignoreIds[] = $post->post_id;
}
$ignoreIdsForMySql = implode(",", $ignoreIds);
$regularProductsSql =
"SELECT p.ID as post_id FROM $wpdb->posts as p
join $wpdb->postmeta pm
on p.ID = pm.post_id
and pm.meta_key='_sku'
AND pm.meta_value LIKE '%$sku%'
join $wpdb->postmeta visibility
on p.ID = visibility.post_id
and visibility.meta_key = '_visibility'
and visibility.meta_value <> 'hidden'";
$regularProductsSql .=
"where 1
and (p.post_parent = 0 or p.post_parent is null)
and p.ID not in ($ignoreIdsForMySql)
and p.post_status = 'publish'
group by p.ID";
$regular_products = $wpdb->get_results($regularProductsSql);
$results = array_merge($variations, $regular_products);
$wp_query->found_posts += sizeof($results);
return $results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment