Last active
February 7, 2021 15:14
-
-
Save devinsays/ca2f2dff2d6fde3bfd1e to your computer and use it in GitHub Desktop.
Code snippet examples showing how to limit search to post types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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