You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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.

Restrict Search Results to Specific Custom Post Types

This is the cleanest, theme-update-safe approach. Here's how to implement it:

  1. Go to your WordPress dashboard → Appearance → Theme File Editor.
  2. 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.php file.
  3. 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' );
    
  4. 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 country and location custom post types.
  • Automatically excludes all other post types (post, page, experience, trip-theme) without needing to edit the search.php template directly.

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:

  1. Open search.php in the Theme File Editor.
  2. Locate the loop section (starts with if ( have_posts() ) :).
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:37:29