前提・実現したいこと
フロントエンドエンジニアのblog様
(https://www.will3in.co.jp/frontend-blog/article/multiple-search-form/)
を参考にサイト内検索をページ別で設置しました、それぞれ条件を設け、検索結果ページを用意したいです。
発生している問題・エラーメッセージ
設置したところ、条件が絞られずサイト内検索どちらともが同じ条件で検索出来る状態です。
また、検索結果のレイアウトも片方のphpだけ読み込まれどちらも同じレイアウトで表示されました。
サイト内検索(1つ目)の記述
<form method="get" id="siteSearch" action="<?php echo home_url('/'); ?>"> <input type="text" name="s" id="searchInput" value="<?php if ( is_post_type_archive('blog') ){ echo get_search_query(); } ?>" placeholder="サイト内検索" /> <input type="submit" value="検索" accesskey="f" /> </form>サイト内検索(2つ目)の記述
<form method="get" id="textsearch" action="<?php echo home_url('/'); ?>"> <input type="text" name="s" id="textsearch" value="<?php the_search_query(); ?>" placeholder="キーワードを入力して下さい。" /> <input type="hidden" name="post_type" value="(カスタム投稿タイプ名)"> <input type="submit" value="検索" accesskey="f" /> </form>functions.phpの記述
add_filter('template_include','custom_search_template');
function custom_search_template($template){
if ( is_search() ){
$post_types = get_query_var('post_type');
foreach ( (array) $post_types as $post_type )
$templates[] = "search-{$post_type}.php";
$templates[] = 'search.php';
$template = get_query_template('search',$templates);
}
return $template;
}
補足
functions.phpに下記を記載したところ、2つ目の検索結果の条件絞り込みができましたが、
1つ目も同様に反映されてしまいました。
function filter_search( $query ) {
if ( $query->is_search() && $query->is_main_query() && ! is_admin() ) {
$query->set( 'post_type', array( '(カスタム投稿タイプ名)' ) );
}
}
add_filter( 'pre_get_posts', 'filter_search' );