让搜索支持所有自定义文章类型,搜索结果排除某些分类的文章,搜索结果排除所有页面

    1. <?php
    2. //让搜索支持所有自定义文章类型
    3. function include_post_types_in_search($query) {
    4. if (is_search()) {
    5. $post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects');
    6. $searchable_types = array();
    7. if ($post_types) {
    8. foreach ($post_types as $type) {
    9. $searchable_types[] = $type->name;
    10. }
    11. }
    12. $query->set('post_type', $searchable_types);
    13. }
    14. return $query;
    15. }
    16. add_action('pre_get_posts', 'include_post_types_in_search');
    17. //搜索结果排除某些分类的文章
    18. function search_filter_category($query) {
    19. if (!$query->is_admin && $query->is_search) {
    20. $query->set('cat', ' , '); //分类的ID,前面加负号表示排除;如果直接写ID,则表示只在该ID中搜索
    21. }
    22. return $query;
    23. }
    24. add_filter('pre_get_posts', 'search_filter_category');
    25. //搜索结果排除所有页面
    26. function search_filter_page($query) {
    27. if ($query->is_search) {
    28. $query->set('post_type', 'post');
    29. }
    30. return $query;
    31. }
    32. add_filter('pre_get_posts', 'search_filter_page');