Skip to content

Instantly share code, notes, and snippets.

@sakihomma
Created June 21, 2018 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakihomma/a6102bf585a3ff784d10bd394970f57c to your computer and use it in GitHub Desktop.
Save sakihomma/a6102bf585a3ff784d10bd394970f57c to your computer and use it in GitHub Desktop.
*WordPress* Add search functionality including custom fields
<?php
/*--------------------------------------*/
/* Custom Search */
/*--------------------------------------*/
/* -------------------------------------*/
/* 1. posts_search */
/* -------------------------------------*/
add_filter( 'posts_search', function( $orig_search, $query ){
if ( $query->is_search() && $query->is_main_query() && ! is_admin() ) :
global $wpdb;
$q = $query->query_vars;
$n = ! empty( $q['exact'] ) ? '' : '%';
$search = '';
$searchand = '';
if( isset($q['search_terms']) ):
foreach ( $q['search_terms'] as $term ) :
$include = '-' !== substr( $term, 0, 1 );
if ( $include ) {
$like_op = 'LIKE';
$andor_op = 'OR';
} else {
$like_op = 'NOT LIKE';
$andor_op = 'AND';
$term = substr( $term, 1 );
}
$like = $n . $wpdb->esc_like( $term ) . $n;
$search .= $wpdb->prepare( "{$searchand}(($wpdb->posts.post_title $like_op %s) $andor_op ($wpdb->posts.post_content $like_op %s) $andor_op (custom.meta_value $like_op %s))", $like, $like, $like );
$searchand = ' AND ';
endforeach;
endif;
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = '') ";
}
return $search;
else :
return $orig_search;
endif;
}, 10, 2 );
/* -------------------------------------*/
/* 2. posts_join */
/* -------------------------------------*/
add_filter( 'posts_join', function( $join, $query ){
if ( $query->is_search() && $query->is_main_query() && ! is_admin() ) :
global $wpdb;
$join .= " INNER JOIN ( ";
$join .= " SELECT post_id, group_concat( meta_value separator ' ') AS meta_value FROM $wpdb->postmeta ";
$join .= " GROUP BY post_id ";
$join .= " ) AS custom ON ($wpdb->posts.ID = custom.post_id) ";
endif;
return $join;
}, 10, 2 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment