Skip to content

Instantly share code, notes, and snippets.

@ReallyBean
Created August 2, 2018 11:30
Show Gist options
  • Save ReallyBean/686d990692d3cd8b7c71a5c6818c5e04 to your computer and use it in GitHub Desktop.
Save ReallyBean/686d990692d3cd8b7c71a5c6818c5e04 to your computer and use it in GitHub Desktop.
Full search including all the custom field in wordpress
/**
* Join posts and postmeta tables
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
*/
function cf_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', '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() ) {
$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' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment