ウィジェットなどで表示する記事検索フォームにプラグインを使わずカテゴリーやタグも検索できるようにする方法です。
たぶん色々と既出かもしれませんが、自分で書くことも大事だと思うので、備忘録も兼ねて投稿します。
以下functions.phpに直接コピペで使えます。バージョン4.3.1で動作確認しました。
/* 検索フォーム生成 */
function my_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >';
// 投稿タイプ
$form .= '<input type="hidden" name="post_type" value="post" />';
// キーワード
$form .= '<div><input type="text" value="' . get_search_query() . '" name="s" id="s" placeholder="キーワード" /></div>';
// カテゴリー
$form .= '<div>' . wp_dropdown_categories( 'echo=0&show_option_all=カテゴリー選択' ) . '</div>';
// タグ
$tags_query = ( isset( $_GET['tag'] ) && is_array( $_GET['tag'] ) ) ? $_GET['tag'] : array();
$form .= '<div>';
foreach (get_tags() as $tag) {
$form .= '<label style="display: inline-block;"><input type="checkbox" name="tag[]" value="' . esc_attr( $tag->slug ) . '" ' . checked( in_array( $tag->slug , $tags_query), true, false ). ' />' . $tag->name . '</label> ';
}
$form .= '</div>';
$form .= '<input type="submit" value="検索" id="searchsubmit" />';
$form .= '</form>';
return $form;
}
add_filter( 'get_search_form', 'my_search_form' );
/* 検索リクエストクエリー整形 */
function custom_parse_request( $query ) {
if ( isset( $_GET['tag'] ) && is_array( $_GET['tag'] ) ) {
// タグ検索は配列だとエラーになるので文字列に変更する
$query->query_vars['tag'] = implode( ',', $_GET['tag'] );
}
return $query;
}
add_action( 'parse_request', 'custom_parse_request' );
/* 検索タイトル変更 */
function custom_title( $title, $sep ) {
if ( is_search() ) {
$title = '検索';
if ( !empty( $sep ) ) {
$title .= ' ' . $sep . ' ';
}
}
return $title;
}
add_filter( 'wp_title', 'custom_title', 10, 2 );
Twenty Tenだとlabelが非表示になっているので、インライン指定で強制的に表示させてます。
この辺はテーマの仕様に応じて変更が必要になりますね。
検索タイトルはそのままだとキーワード未入力の場合タイトルが「 | 検索結果: | サイトタイトル」って感じで変になってしまうので「検索 | サイトタイトル」となるようにしています。