Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm trying to limit a search to only pages, but it isn't working properly. When I include this hidden field in the search form:

<input type="hidden" name="post_type" value="page" />

The results include posts, pages, and custom post types. If I change the above to search only posts, it works properly, and only posts are displayed. Anyone have any ideas why it won't properly restrict my post to only display pages?

I need to restrict the results for this search form only, so modifying the search query results in the search results template or in functions.php won't work for me.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

A quick test on a default install with TwentyEleven confirms this, and I'm not sure why this is the case, however there is a way you can do this via your functions.php.

add a hidden field to the form with your own query var:

<input type="hidden" name="my_type" value="page" />

or:

<input type="hidden" name="my_type" value="post,page" />

add the new query var to WP's recognized query vars:

function wpse50828_query_vars( $query_vars ){
    $query_vars[] = 'my_type';
    return $query_vars;
}
add_filter( 'query_vars', 'wpse50828_query_vars' );

add your code to set the post type when that query var is set:

function wpse50828_search( $query ){
    if( get_query_var('my_type') )
        $query->set('post_type', explode( ',', get_query_var('my_type') ));

    return $query;
}
add_action( 'parse_query','wpse50828_search' );
share|improve this answer
    
brilliant. Thanks. Anyway to have it return both posts and pages? –  John Chandler May 2 '12 at 2:49
    
@JohnChandler see edited code above –  Milo May 2 '12 at 3:25
    
that did it. thanks! –  John Chandler May 2 '12 at 3:46
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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