1
1

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 5 years have passed since last update.

WordPress カスタム投稿タイプ 検索機能

Last updated at Posted at 2019-08-23

目標

カスタム投稿タイプの一覧画面に検索機能を追加する
投稿タイプを news とした場合のサンプル

アーカイブページに検索フォームを設置する

<form name="search" method="get">
    <input type="text" name="text" value="<?= esc_attr(get_query_var('text')) ?>" >
</form>

独自のクエリーストリングを許可する

この設定をすることで、 $wp->query_string に含まれたり、 get_query_var('text') で取得できる。
※ WordPressがデフォルトで用意してあるものがあるので、重複しないように注意。
 https://wpdocs.osdn.jp/WordPress_Query_Vars

function my_query_vars($vars)
{
	$vars[] = 'text';

	return $vars;
}

add_filter('query_vars', 'my_query_vars');

メインクエリをフックする

function my_pre_get_posts($query)
{
	if (is_admin() || ! $query->is_main_query()) {
		return;
	}
	if ($query->is_post_type_archive('news')) {
		/** @var WP $wp */
		global $wp;

		$params = [];
		parse_str($wp->query_string, $params);

		if (isset($params['text'])) {
			$query->set('s', $params['text']);
		}

		// 以下は本題とは違うが、1ページあたりの件数と、表示順もここで設定できるので
		// 一覧画面で表示件数を動的に変更したり、並び順を動的に変更することが可能
		$query->set('posts_per_page', 12);
		$query->set('orderby', ['post_date' => 'DESC']);
	}
}

add_action('pre_get_posts', 'my_pre_get_posts');
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?