function cf_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', 'cf_search_join' );
function cf_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 );
// 特定のカスタムフィールドを検索対象から外す(※1)
// $where .= " AND (" . $wpdb->postmeta . ".meta_key NOT LIKE 'number')";
// $where .= " AND (" . $wpdb->postmeta . ".meta_key NOT LIKE 'zip')";
// $where .= " AND (" . $wpdb->postmeta . ".meta_key NOT LIKE 'access')";
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT";
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
// 検索対象を『タイトルのみ』にする
function __search_by_title_only( $search, & $wp_query ) {
global $wpdb;
if ( empty( $search ) )
return $search; // skip processing - no search term in query
$q = $wp_query->query_vars;
$n = !empty( $q[ 'exact' ] ) ? '' : '%';
$search =
$searchand = '';
foreach ( ( array )$q[ 'search_terms' ] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
$searchand = ' AND ';
}
if ( !empty( $search ) ) {
$search = " AND ({$search}) ";
if ( !is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = '') ";
}
return $search;
}
//add_filter( 'posts_search', '__search_by_title_only', 500, 2 );// (※2)
下記サイトを参考にしました。
WordPress内の検索対象にカスタムフィールドも適用する