Created
July 25, 2019 10:35
-
-
Save zevilz/cae90ea13f70a5c4af43b6874faa85c8 to your computer and use it in GitHub Desktop.
Include post meta fields in WP search.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add post meta to search query in where part | |
* | |
* @param string $where Where query part | |
* | |
* @return string | |
*/ | |
function modify_wp_search_where( $where ) { | |
if ( is_search() ) { | |
global $wpdb, $wp; | |
$where = preg_replace( | |
"/($wpdb->posts.post_title LIKE '{$wpdb->placeholder_escape()}{$wp->query_vars['s']}{$wpdb->placeholder_escape()}'\))/i", | |
"$0 OR ($wpdb->postmeta.meta_value LIKE '%{$wp->query_vars['s']}%')", | |
$where | |
); | |
add_filter( 'posts_join_request', 'modify_wp_search_join' ); | |
add_filter( 'posts_distinct_request', function() { | |
return 'DISTINCT'; | |
} ); | |
} | |
return $where; | |
} | |
add_action( 'posts_where_request', 'modify_wp_search_where' ); | |
/** | |
* Join post meta to search query | |
* | |
* @param string $join Join query part | |
* | |
* @return string | |
*/ | |
function modify_wp_search_join( $join ) { | |
global $wpdb; | |
return $join .= " LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) "; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment