Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pareshsojitra/f56962453d89a5b598d81b27c57346a3 to your computer and use it in GitHub Desktop.
Save pareshsojitra/f56962453d89a5b598d81b27c57346a3 to your computer and use it in GitHub Desktop.
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