Created
October 19, 2018 11:35
-
-
Save nfsarmento/75a691de453dd4fc146af181eea78e28 to your computer and use it in GitHub Desktop.
Extend WordPress search to include custom fields
This file contains 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
/** | |
* Extend WordPress search to include custom fields | |
* | |
* https://www.nuno-sarmento..com | |
*/ | |
/** | |
* Join posts and postmeta tables | |
* | |
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join | |
*/ | |
function ns_search_join( $join ) { | |
global $wpdb; | |
if ( is_search() ) { | |
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id '; | |
} | |
return $join; | |
} | |
add_filter('posts_join', 'ns_search_join' ); | |
/** | |
* Modify the search query with posts_where | |
* | |
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where | |
*/ | |
function ns_search_where( $where ) { | |
global $pagenow, $wpdb; | |
if ( is_search() ) { | |
$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', 'ns_search_where' ); | |
/** | |
* Prevent duplicates | |
* | |
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct | |
*/ | |
function ns_search_distinct( $where ) { | |
global $wpdb; | |
if ( is_search() ) { | |
return "DISTINCT"; | |
} | |
return $where; | |
} | |
add_filter( 'posts_distinct', 'ns_search_distinct' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment