Skip to content

Instantly share code, notes, and snippets.

@hmowais
Created November 27, 2019 21:00
Show Gist options
  • Save hmowais/3b1d749f191618ed71e6c6c99e079c7b to your computer and use it in GitHub Desktop.
Save hmowais/3b1d749f191618ed71e6c6c99e079c7b to your computer and use it in GitHub Desktop.
Modify WordPress Default Search (Add Product Sku's)
<?php
/** __________________________________ ENHANCE THE STANDARD SEARCH
* Join posts and postmeta tables
* This one hels to include the SKU in tzhe standard search
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
*/
function cf_search_join( $join ) {
global $wpdb;
if ( is_search() || !empty($_REQUEST['s'] )) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
add_filter('posts_join', 'cf_search_join' );
/**
* Modify the search query with posts_where
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
*/
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() || !empty($_REQUEST['s'] ) ) {
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
/**
* Prevent duplicates
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
*/
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() || !empty($_REQUEST['s'] ) ) {
return "DISTINCT";
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
/* END Search includes SKU */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment