ワードプレスの標準の検索機能では、タイトルと本文に検索文字列が含まれるかどうかだけを調べて、検索結果を表示するだけなので、htmlのタグや属性値なども検索結果としてヒットします。
ワードプレスを構築する中で、検索機能は重要なテーマの一つです。
検索範囲や内容のカスタマイズの手がかりをpost_search hookを使い探してみました
coreファイルの検索の仕組みと、snippet
wp-includes/query.php
// If a search pattern is specified, load the posts that match
if ( !empty($q['s']) ) {
// added slashes screw with quote grouping when done early, so done later
$q['s']= stripslashes($q['s']);
if ( !empty($q['sentence']) ) {
$q['search_terms']= array($q['s']);
} else {
preg_match_all('/".*?(" |$) |((?<=[\r\n\t ",+]) |^)[^\r\n\t ",+]+/', $q['s'], $matches);
$q['search_terms']= array_map('_search_terms_tidy', $matches[0]);
}
$n= !empty($q['exact']) ? '' : '%';
$searchand= '';
foreach( (array) $q['search_terms'] as $term ) {
$term= esc_sql( like_escape( $term ) );
$search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))";
$searchand= ' AND ';
}
if ( !empty($search) ) {
$search= " AND ({$search}) ";
if ( !is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password= '') ";
}
}
// Allow plugins to contextually add/remove/modify the search section of the database query
$search= apply_filters_ref_array('posts_search', array( $search, &$this ) );
ワードプレスの標準の検索機能では、タイトルと本文に検索文字列が含まれるかどうかだけを調べて、検索結果を表示するだけなので、htmlのタグや属性値なども検索結果としてヒットします。
この問題に対応するためには、post_search hookを使います。
add_filter( 'posts_search', 'my_test' );
function my_test($content){
return str_replace('wp_posts.post_content', 'wp_posts.post_excerpt', $content );
}
引数$contentの中身は、以下のようになるので、
string() " AND (((wp_posts.post_title LIKE '%keyword%') OR (wp_posts.post_content LIKE '%keyword%'))) "
my_test()では、投稿内を検索するSQLを抜粋を検索するように変更しています。
抜粋の中に検索対象文字列が存在するように対処が必要です。