Skip to content

Instantly share code, notes, and snippets.

@strsar
Created October 7, 2021 01:38
Show Gist options
  • Save strsar/3b7be1b90af906a335b99bee8ac0e0ac to your computer and use it in GitHub Desktop.
Save strsar/3b7be1b90af906a335b99bee8ac0e0ac to your computer and use it in GitHub Desktop.
[WP] Search helpers + include all meta fields in default search query
<?php defined('ABSPATH') or header('Location: /');
/**
* Fix search when using smart quotes. Downgrade to straight double quotes.
*/
add_filter('pre_get_posts', 'filter_smart_quote_queries', 10, 1);
add_action('pre_get_posts', 'exclude_posts_from_search');
/**
* Add custom fields data to global WP search
*
* @reference https://generatepress.com/forums/topic/how-can-i-include-advanced-custom-fields-data-in-search-results/
*/
add_filter('posts_join', 'acf_search_join');
add_filter('posts_where', 'acf_search_where');
add_filter('posts_distinct', 'acf_search_distinct');
/**
* Fix (convert) "smart" quotes
*/
function filter_smart_quote_queries($query) {
if(!empty($query->query['s'])) {
$search_term = $query->query['s'];
$search_term = str_replace(array('"', '"', '\&#34;'), '"', $search_term); // Smart (curly) double quote > straight double quote
unset($query->query['s']);
$query->set('s', $search_term);
}
return $query;
}
/**
* Exclude from search
*/
function exclude_posts_from_search($query){
if($query->is_main_query() && is_search()){
$post_ids = get_field('exclude_from_search', 'option'); //Exclude posts by ID
$query->set('post__not_in', $post_ids);
}
}
/**
* Join posts and postmeta tables
*
* @see http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
*/
function acf_search_join($join) {
global $wpdb;
if(is_search()) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
/**
* Modify the search query with posts_where
*
* @see http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
*/
function acf_search_where($where) {
global $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;
}
/**
* Prevent duplicates
*
* @see http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
*/
function acf_search_distinct($where) {
global $wpdb;
if(is_search()) {
return "DISTINCT";
}
return $where;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment