特定のタクソノミーターム(カテゴリ、タグなど)に結果を限定する
ネイティブ/デフォルトの検索結果に適用する
カテゴリ(または他のタクソノミーターム)を選択できるように検索フォームを作成する代わりに、次のようにしたい場合:
ネイティブ/デフォルトの検索結果を常に特定のカテゴリに制限したい場合は、次のように\SearchWP\Modを使用できます。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Limit SearchWP Native/Default results to Category that has 'foobar' slug. | |
| add_filter( 'searchwp\native\args', function( $args, $query ) { | |
| if ( ! isset( $args['tax_query'] ) || ! is_array( $args['tax_query'] ) ) { | |
| $args['tax_query'] = []; | |
| } | |
| $args['tax_query'][] = [ | |
| 'taxonomy' => 'category', | |
| 'field' => 'slug', | |
| 'terms' => 'foobar', | |
| ]; | |
| return $args; | |
| }, 20, 2 ); |
この\SearchWP\Modは、すべてのネイティブ/デフォルトの検索に適用されることに注意してください。
プログラムによる検索クエリ
カテゴリ(または他のタクソノミーターム)を選択できるように検索フォームを作成する代わりに、次のようにしたい場合:
検索クエリを常に特定のタクソノミーターム(この場合はカテゴリ)にプログラムで制限する
次のように、SWP_Queryのtax_queryパラメータを使用できます。
All hooks should be added to your custom SearchWP Customizations Plugin.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Limit SearchWP results to Category that has 'foobar' slug. | |
| $search = new \SWP_Query( [ | |
| 's' => 'coffee', // Search string. | |
| 'tax_query' => [ [ | |
| 'taxonomy' => 'category', | |
| 'field' => 'slug', | |
| 'terms' => 'foobar', | |
| ] ], | |
| ] ); | |
| // Print all results. | |
| print_r( $search->posts ); |
tax_queryは、WP_Queryが機能するのと同じ方法で、複数の条件に対応できます。

