如何在WordPress中控制搜索结果仅显示指定自定义文章类型
Got it, let's get this sorted for you! Since you're using the Twenty Seventeen theme, the most reliable way to limit your search results to only the country and location custom post types (while hiding post, page, experience, and trip-theme) is to use a WordPress hook—this avoids editing core theme files directly, which would get overwritten when the theme updates.
Recommended Method: Use the pre_get_posts Hook
This is the cleanest, theme-update-safe approach. Here's how to implement it:
- Go to your WordPress dashboard → Appearance → Theme File Editor.
- Select your active theme (Twenty Seventeen, or a child theme if you’ve set one up—child themes are even safer for customizations) and open the
functions.phpfile. - Paste the following code at the very end of the file:
function restrict_search_to_target_cpts( $query ) { // Only modify the main frontend search query (ignore admin searches) if ( $query->is_search() && $query->is_main_query() && !is_admin() ) { // Define the post types you want to include in results $query->set( 'post_type', array( 'country', 'location' ) ); } } add_action( 'pre_get_posts', 'restrict_search_to_target_cpts' ); - Click Update File to save your changes.
What This Code Does
- It checks if we’re dealing with the main search query on the frontend (so it won’t interfere with admin area searches).
- It overrides WordPress’s default search behavior to only pull results from your
countryandlocationcustom post types. - Automatically excludes all other post types (
post,page,experience,trip-theme) without needing to edit thesearch.phptemplate directly.
Alternative: Modify search.php (Not Recommended)
If you prefer to edit the template file directly (note: this change will be lost if you update the Twenty Seventeen theme), you can add a conditional check inside the loop:
- Open
search.phpin the Theme File Editor. - Locate the loop section (starts with
if ( have_posts() ) :). - Inside the loop, add a check before displaying post content:
while ( have_posts() ) : the_post(); // Only display posts from the allowed custom post types if ( get_post_type() === 'country' || get_post_type() === 'location' ) : // Keep the existing post display code here (e.g., get_template_part( 'template-parts/post/content', 'excerpt' ); ) endif; endwhile;
Again, the pre_get_posts hook method is strongly preferred because it’s more maintainable long-term.
内容的提问来源于stack exchange,提问作者Suresh Kumar

