Wordpress - Search in Custom Post Type Only

2019-09-11 09:05发布

问题:

I have a website with a blog and a custom post_type for Videos (named video). Along with various taxonomies attached to it (Video Categories, Video Tags, etc.)

I am trying to set up a search function to search just the video taxononmy and another to search just the blog taxonomy. There will be a search box in each of these pages to slim down the results.

Here is what I have done so far.

<aside id="sub-search" class="widget widget_search">
        <form class="search-form" action="http://www.studiobenna.com/jf/" method="get" role="search">
            <label>
                <span class="screen-reader-text">Search for:</span>
                <input class="search-field" type="search" name="s" value="long" placeholder="Search Videos">
            </label>
            <input type="hidden" name="post_type" value="video" />
            <input class="search-submit" type="submit" value="Search">
        </form>
    </aside>

Which results in the url ending in: http://example.com/?s=video&post_type=video

But this doesn't filter only the video taxonomy. I have one that references post_type=post for the regular blog search.

What is the correct way to query the Wordpress search function in the URL to only return one post type? I am using the WP Extended Search plugin to allow a search box at the top right of the screem to search the entire site.

I also want these searches to be limited to post type but also pickup any categories and tags attached to them (I don't know if this is any extra step).

An example of what I am doing is here http://www.studiobenna.com/jf/?page_id=8 in the search box next to browse. If you type in Blog here there should be only one result title "Great Western Loop" but others come back.

I have tried adding this to my functions.php:

function mySearchFilter($query) {
    $post_type = $_GET['post_type'];
    if (!$post_type) {
        $post_type = 'any';
    }
    if ($query->is_search) {
        $query->set('post_type', $post_type);
    };
    return $query;
};

add_filter('pre_get_posts','mySearchFilter');

But it doesn't work. I also tried adding this to the search.php page right before the if (have_posts) loop:

<?php

            if(isset($_GET['post_type'])) {
                $type = $_GET['post_type'];
                $args = array( 'post_type' => $type );
                $args = array_merge( $args, $wp_query->query );
            query_posts( $args );    
            }
        ?>

Still nothing.

回答1:

Everything is correct except the post_type set of the query.

This will work correctly for your case:

function mySearchFilter( $query ) {
    $post_type = $_GET['post_type'];
    if (!$post_type) {
       $post_type = 'any';
    }
    if ( $query->is_search ) {
       $query->set( 'post_type', array( esc_attr( $post_type ) ) );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'mySearchFilter' );