Skip to content

Instantly share code, notes, and snippets.

@jhealey5
Created July 4, 2016 08:29
Show Gist options
  • Select an option

  • Save jhealey5/65a8506c8dd9420fa9423899acef0f2e to your computer and use it in GitHub Desktop.

Select an option

Save jhealey5/65a8506c8dd9420fa9423899acef0f2e to your computer and use it in GitHub Desktop.
Search all fields
/**
* Add Join to search query
* Part 1 of 3 part functions to add ACF fields to search page results
*
* @param $join
* @return mixed
*/
function acf_search_join( $join ) {
global $wpdb;
if ( is_search() && is_main_query() ) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
add_filter('posts_join', 'acf_search_join' );
/**
* Add meta value to where query
* Part 2 of 3 part functions to add ACF fields to search page results
*
* @param $where
* @return mixed
*/
function acf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() && is_main_query() ) {
$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 );
//Make sure we don't find results for ACF generated meta_value -> ACF field entries
$where = " AND (".$wpdb->postmeta.".meta_value NOT REGEXP 'field_[a-z0-9]{13}')" . $where;
}
return $where;
}
add_filter( 'posts_where', 'acf_search_where' );
/**
* Force distinct on where query
* Part 3 of 3 part functions to add ACF fields to search page results
*
* @param $where
* @return string
*/
function acf_search_distinct( $where ) {
global $wpdb;
if ( is_search() && is_main_query() ) {
return "DISTINCT";
}
return $where;
}
add_filter( 'posts_distinct', 'acf_search_distinct' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment