2
votes

I'm trying to limit my WordPress search to a single, custom post type.

It seems I can change most parameters of the search query, except the post type variable.

$query_args = explode("&", $query_string);
$search_query = array();

foreach($query_args as $key => $string) {
    $query_split = explode("=", $string);
    $search_query[$query_split[0]] = urldecode($query_split[1]);
}

$search_query['post_type'] = 'thread';

$search = new WP_Query($search_query);

This query will still return all post types. But if I set a different parameter, like 'posts_per_page', it works fine.

What's going on? How can I limit my search query to a custom post type?

Thanks for your help!

EDIT: btw, I'm using WP 3.4.2

1

1 Answers

4
votes

Place this in your functions.php file. :)

<?php
add_filter('pre_get_posts', 'filter_search_cpt_threads');
/** filter search for threads CPT */
function filter_search_cpt_threads($query)
{
    if( $query->is_search ) $query->set('post_type', array('thread'));

    return $query;
}
?>

Best!
R