Skip to content

Instantly share code, notes, and snippets.

@devinsays
Last active February 7, 2021 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save devinsays/ca2f2dff2d6fde3bfd1e to your computer and use it in GitHub Desktop.
Save devinsays/ca2f2dff2d6fde3bfd1e 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