Skip to content

Commit

Permalink
Adds filters to search post meta using default WP search (#393)
Browse files Browse the repository at this point in the history
  • Loading branch information
coreymcollins authored and gregrickaby committed Sep 25, 2018
1 parent 4278c82 commit 8e15270
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
5 changes: 5 additions & 0 deletions functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
70 changes: 70 additions & 0 deletions inc/acf-search.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php
/**
* ACF/Post Meta Search.
*
* Extend WordPress search to include custom fields.
* https://adambalee.com
*
* @package _s
*/

/**
* Join posts and postmeta tables
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
*
* @param string $join The SQL query.
* @return $join The updated query.
* @author Corey Collins
*/
function _s_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', '_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' );

0 comments on commit 8e15270

Please sign in to comment.