0

I have created several custom content types.

My question: What about showing things of different content types in search.php? Are different post types shown in search.php? if not how to make them shown? How should I configure the search code in order to show these content types which I want to show?

3

By default it is usually posts and pages, but, you can modify this several ways

URLs

example.com/?s=test will search for the term test in posts and pages, but, example.com/?s=test&post_type=product will search posts of the type product for the term test.

In the same way appending ?s=term to your post type archive URL will search that archive for that term, as it will by appending it to various other URLs

Query filters

You can modify the following code to do the post type adjustment automatically without needing the above change:

function filter_search($query) {
    if ($query->is_search) {
        $query->set('post_type', array('post', 'page', 'customposttype'));
    };
    return $query;
};
add_filter('pre_get_posts', 'filter_search');

Some people advise that you add a query_posts line above your post loop in your search template. I advise against this as this means an additional unnecessary database query, and it overrides any filters and hooks that try to add features or improve the search query

Specific individual Search for individual custom post types

See here:

http://wpsnipp.com/index.php/template/create-multiple-search-templates-for-custom-post-types/

1

There are two parts to this - when you register your post types you need to make sure they are not excluded from search - exclude_from_search=true.

Then you need to add the post_type to your search loop. To do so you can add a filter to your search query by placing this in functions.php:

function filter_search($query) {
    if ($query->is_search) {
    $query->set('post_type', array('post', 'YOUR POST TYPE'));
    };
    return $query;
};
add_filter('pre_get_posts', 'filter_search');

This search will only return posts and YOUR POST TYPE, no pages or whatnot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.