Forked from devinsays/limit-search-to-post-types.php
Created
February 7, 2021 15:14
-
-
Save pareshsojitra/f56962453d89a5b598d81b27c57346a3 to your computer and use it in GitHub Desktop.
Code snippet examples showing how to limit search to post types
This file contains hidden or 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