0

I created a custom post type that will not be displayed anywhere on the site. However, I want to access the data from a search form. Because there will be a lot of pages, I need to disable the post type from showing up in the normal search and create a second search page for only searching the keyword in custom post types.

I've read quite a few pages and people give different advice and sometimes say to avoid certain functions, so I'm not sure what is the most updated way to do this.

I started by cutting and pasting my "search.php" into 2 partial templates and then changing "search.php" to

<?php
if(isset($_GET['search-type'])) {
    $type = $_GET['search-type'];
    if($type == 'custom-post-type') {
        get_template_part('/partials/search-custom-post-type');

    } else{
        get_template_part('/partials/search-normal');
    }
}
else{
        get_template_part('/partials/search-normal');
    }
?>

I read that I could add the following code and it would allow me to customize the search-custom-post-type.php

$args = array( 'post_type' => 'custom-post-type-name' );
$args = array_merge( $args, $wp_query->query );
query_posts( $args );

However, this doesn't do anything. The search is still the same.

0

For the main search page, you can use pre_get_posts with a conditional:

if($query->is_main_query() && $query->is_search && !is_admin()) {

So only if it's the main query, it's a search query, and you're not in the admin, adjust the query. Set whatever post types you DO want indexed in the main search query.

Next step, setting up a custom search. Depending on how you want this set up, one option is to create a Page template that first checks for a query string (i.e. a submitted search). If it finds a $_GET['customsearch'] parameter, display search results by using a custom WP_Query to pull results from only your CPT. If not, then display a search form (with customsearch as the name of the input).

Another option would be to create a widget which you can stick into any sidebar on the website, and have the form action be a Page with a custom Page template such that if $_GET['customsearch'] is empty the template does a wp_redirect before outputting header/etc. (you can redirect to homepage or whatever page is most relevant), but if there is a parameter it displays search results (again with a custom WP_Query).

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.