この記事は最後に更新してから1年以上経過しています。

6.2に追加されるsearch_columnsパラメータが便利

説明

バージョン6.2では記事検索機能を備えたWP_Queryクラスにsearch_columnsパラメータが追加される。標準のキーワード検索では、タイトル(post_title)、本文(post_content)、抜粋(post_excerpt)が対象になっているが、search_columnsパラメータを使うと対象を絞り込めるようになる。

search_columnsパラメータ

まずはsearch_columnsパラメータの仕様を確認。Docコメントには次のように記述されており、'post_title'、'post_excerpt'、'post_content'の組み合わせを配列で指定できるようだ。

Array of column names to be searched. Accepts 'post_title',
'post_excerpt' and 'post_content'. Default empty array.

search_columnsパラメータの効果を確認するため、タイトルに「world」が含まれる投稿とは別に、本文に「world」を含めた投稿を追加する。まずはこれで「world」が含まれる投稿を検索してみる。

$query = new WP_Query( ['s'=>'world'] );
if ( is_array( $query->posts ) ) {
	foreach ( $query->posts as $post ) {
		printf( '%d: %s<br />', $post->ID, esc_html( $post->post_title ) );
	}
}

上記のコードの実行結果は次の通りで2つの投稿が検索された。

1: Hello world!
1030: 本文に〇〇!

今度はsearch_columnsパラメータに'post_title'のみの配列を追加してみる。

$query = new WP_Query( [
	's'              => 'world',
	'search_columns' => ['post_title']
	] );

これで検索結果は1件となり、タイトルに「world」が含まれるもののみとなった。

1: Hello world!

次はsearch_columnsパラメータの'post_title'を'post_content'に変更してみる。

$query = new WP_Query( [
	's'              => 'world',
	'search_columns' => ['post_content']
	] );

この場合の検索結果は、本文に「world」が含まれ1件のみとなった。

1030: 本文に〇〇!

以上のように、バージョン6.2ではWP_Queryクラスにsearch_columnsパラメータを指定することで、キーワード検索の対象を限定できるようになった。

post_search_columnsフィルター

バージョン6.2ではsearch_columnsパラメータの追加にあわせてpost_search_columnsフィルターが追加された。

$search_columns = (array) apply_filters( 'post_search_columns', $search_columns, $search, $query );

このフィルターの第1パラメータ$search_columnsにはWP_Queryオブジェクトが受け取ったsearch_columnsパラメータをパースした内容が格納されており、このフィルターを使用することでキーワード検索の対象を変更できる。

なおこのフィルターの返り値はデフォルトの検索対象である3つのカラムと比較され、3つのカラム以外は検索対象にはならない。仮に'post_name'を含めてもそれが検索対象になることはない。


最終更新 : 2023年03月30日 12:40


お勧め

wp_get_post_terms(2014年7月4日 更新)

mixed wp_get_post_terms( [ int $post_id = 0 [ , string $taxonomy = 'post_tag' [ , array $args = array() ] ] ] )
投稿記事のタクソノミー情報を取得する。

add_action(2023年7月28日 更新)

bool add_action( string $tag, mixed $function_to_add [ , int $priority = 10 [ , int $accepted_args = 1 ] ] )
WordPressシステムの関数にアクション関数を追加する。

get_editor_stylesheets(2014年9月5日 更新)

array get_editor_stylesheets( )
エディタ向けのスタイルシートURLを取得する。

wp_count_terms(2020年12月14日 更新)

array | int | WP_Error wp_count_terms( array | string $args = array() [ , array | string $deprecated = '' ] )
タクソノミーのターム数を取得する。

the_comments_navigation(2018年5月27日 更新)

void the_comments_navigation( [ array $args = array() ] )
コメントナビゲーションを表示する。