検索結果で使用するテンプレートを投稿とカスタム投稿タイプで…

とある案件で通常の投稿とカスタム投稿タイプで検索結果(seach.php)の振り分けをすることに
その方法を忘れないうちに覚書しました。
searchform.phpのカスタマイズ
まず、searchform.phpのカスマイズですが投稿の検索フォームとカスタム投稿タイプの検索フォームを別々に作成します。
条件分岐で表示させるページを指定します。
<?php if ( is_singular( 'custom' ) || is_post_type_archive( 'custom' ) || is_tax( 'custom_category' ) ): ?> <form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <div> <label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label> <input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder="カスタム投稿タイプの検索" /> <input type="submit" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" /> <input type="hidden" name="post_type" value="custom"> </div> </form> <?php else: ?> <form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <div> <label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label> <input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder="投稿の検索" /> <input type="submit" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" /> <input type="hidden" name="post_type" value="post"> </div> </form> <?php endif; ?>
この場合ですとカスタム投稿タイプ”custom”の記事を見ている時と、”custom”のアーカイブを見ている時と、”custom_category”のカテゴリーを見ているときはカスタム投稿タイプの検索フォームを表示し
それ以外は通常のフォームを表示します。
隠しデータのvalue指定で”post”ですと通常の投稿のみの検索、”custom”ですと指定したカスタム投稿タイプのみ検索対象とします。
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 に記述を加えることで、”search-●●●.php” や”search-▲▲▲.php” というカスタム投稿タイプ用のsearch.phpが使えるようになります。
まとめ
検索結果の振り分けって意外に使うものですね。
ポイントとしてはフォームの隠しデータの指定と、条件分岐。
これに限るかなと思います。