Create a gist now

Instantly share code, notes, and snippets.

Code snippet examples showing how to limit search to post types
<?php
// Change search function globally to search only post, page and portfolio post types
function prefix_limit_post_types_in_search( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'post','page', 'portfolio' ) );
}
return $query;
}
add_filter( 'pre_get_posts', 'prefix_limit_post_types_in_search' );
?>
/* Hidden input field that can be added to search form */
<input type="hidden" name="post_type" value="portfolio">
<?php
// Output a search for that only searches portfolio post types
$search = get_search_form( false );
$find = '</form>';
$replace = '<input type="hidden" name="post_type" value="portfolio">' . $find;
$search = str_replace( $find, $replace, $search );
echo $search;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment