From 8e152709c987452efcff88ba95e029f0f1d19d9d Mon Sep 17 00:00:00 2001 From: Corey M Collins Date: Tue, 25 Sep 2018 13:47:16 -0500 Subject: [PATCH] Adds filters to search post meta using default WP search (#393) --- functions.php | 5 ++++ inc/acf-search.php | 70 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 inc/acf-search.php diff --git a/functions.php b/functions.php index 1e8756c10..237c3b4c6 100644 --- a/functions.php +++ b/functions.php @@ -151,6 +151,11 @@ function _s_widgets_init() { */ require get_template_directory() . '/inc/acf.php'; +/** + * Load custom ACF search functionality. + */ +require get_template_directory() . '/inc/acf-search.php'; + /** * Load custom filters and hooks. */ diff --git a/inc/acf-search.php b/inc/acf-search.php new file mode 100644 index 000000000..f8b843590 --- /dev/null +++ b/inc/acf-search.php @@ -0,0 +1,70 @@ +postmeta . ' ON ' . $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id '; + } + + return $join; +} +add_filter( 'posts_join', '_s_search_join' ); + +/** + * Modify the search query with posts_where. + * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where + * + * @param string $where The SQL query. + * @return $where The updated query. + * @author Corey Collins + */ +function _s_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', '_s_search_where' ); + +/** + * Prevent duplicates. + * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct + * + * @param string $where The SQL query. + * @return $where The updated query. + * @author Corey Collins + */ +function _s_search_distinct( $where ) { + global $wpdb; + + if ( is_search() ) { + return 'DISTINCT'; + } + + return $where; +} +add_filter( 'posts_distinct', '_s_search_distinct' );