0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Wordpressのブログに、記事のキーワード検索機能を追加する方法

Posted at

キーワード検索を置きたいページのphpファイルを開く

通常はブログ一覧であるarchive.phpやsingle.phpだと思うのでそのファイルを開いて以下を追加します。

<form action="<?php echo site_url('/ブログがあるディレクトリ/'); ?>" method="get">
  <div class="">
    <input class="" type="text" name="s" value="<?php echo esc_html(get_search_query()); ?>" placeholder="キーワード検索">
    <button class="" type="submit">検索</button>
  </div>
</form>

name="s"をinputタグにつける点がポイントです。
Wordpressはデフォルトでキーワード検索の機能を持っています。
この機能を呼び出す鍵になるのがname="s"です。
sは、WordPressの内部的なクエリ変数で、検索クエリに割り当てられています。
WordPressはこのクエリ変数を使用してデータベース内の投稿ページを検索します。

検索結果ページ(通常search.phpテンプレートファイルが使用される)が表示され、一致する投稿がリストされます。そして、検索結果が表示されるページは、ブログのURL/?s=検索窓に入れたキーワードとなります。

全角スペース繋ぎだと複数キーワード検索ができない

デフォルトだと、複数キーワード検索は半角スペース繋ぎでなければ動きません。
全角スペース繋ぎでも複数キーワードを検索できる様にするためには、function.phpは以下のように追加して、全角スペースを半角スペースへ変換させる様にする必要があります。

function.php
function convert_fullwidth_space_to_halfwidth( $query ) {
    if ( is_search() && !is_admin() ) {
        $s = $query->get( 's' );
        $s = str_replace( ' ', ' ', $s ); // 全角スペースを半角スペースに変換
        $query->set( 's', $s );
    }
    return $query;
}

add_filter( 'pre_get_posts', 'convert_fullwidth_space_to_halfwidth' );

検索対象

この検索窓で検索できる対象は、以下の通りです、カテゴリやタグは含まれません。
含めるためにはカスタムが必要です。

  • 投稿(記事)のタイトル
  • 投稿(記事)の本文(コンテンツ)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?