pre_get_postsを使う場合は、管理画面にまで反映してしまわないよう注意

この記事は公開から1年以上経過しており、内容が古くなっている可能性があります。

WordPressメモ。

サイトの検索にて、post_typeを絞ろうと、functions.phpに

function include_post_type($query) {
	if ($query->is_search()) {
		$query->set('post_type', array('post','xxx','xxx'));
	}
}
add_action( 'pre_get_posts', 'include_post_type' );

と記述したのですが、管理画面の検索にまでこれが反映されてしまいました。

正確には

function include_post_type($query) {
	if (!$query -> is_admin && $query->is_search()) {
		$query->set('post_type', array('post','xxx','xxx'));
	}
}
add_action( 'pre_get_posts', 'include_post_type' );

というように、「!$query -> is_admin」も必要だったみたいですね。

いきなり管理画面の検索がおかしくなったからあせったわ~^^;

 

参考サイト

query_postsを捨てよ、pre_get_postsを使おう【追記あり】【報告あり】 | notnil creation weblog

コメント

タイトルとURLをコピーしました