在WordPress中,如果你想要限制搜索结果只显示当前内容所属分类下的文章,你可以通过修改主题的 searchform.php 文件来实现。以下是一个示例代码,展示了如何实现这一功能:

  1. 打开 searchform.php 文件:

这个文件通常位于你的主题目录下。如果没有这个文件,你可以从默认主题中复制一个。

  1. 修改搜索表单:

searchform.php 文件中,找到搜索表单的代码,并添加一个隐藏的输入字段来存储当前分类的ID。

<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <label> <span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ); ?></span> <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ); ?>" value="<?php echo get_search_query(); ?>" name="s" /> </label> <?php // Get the current wodepress category ID if ( is_category() ) { $current_category = get_queried_object_id(); } else { $current_category = 0; } ?> <input type="hidden" name="cat" value="<?php echo esc_attr( $current_category ); ?>"> <button type="submit" class="search-submit"><?php echo esc_html_x( 'Search', 'submit button' ); ?></button> </form> 3. 修改 search.php 文件:

search.php 文件中,添加一个条件来检查搜索结果是否只包含当前分类的文章。

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); // Display search results endwhile; else : // Display no result information endif;

// Check whether to only search for articles under the current category if ( isset( $_GET['cat'] ) && $_GET['cat'] != 0 ) { $current_category = intval( $_GET['cat'] ); $args = array( 'category__in' => array( $current_category ), 's' => get_search_query(), ); $search_query = new WP_Query( $args ); if ( $search_query->have_posts() ) : while ( $search_query->have_posts() ) : $search_query->the_post(); // wodepress.com displays search results endwhile; wp_reset_postdata(); else : // wodepress.com shows no result information endif; } ?> 按照上面的方法,你可以确保搜索结果只包含当前内容所属分类下的文章。这样,用户在搜索时只会看到与当前分类相关的文章,从而提高搜索的准确性和用户体验。

原文 https://www.jianzhanpress.com/?p=8139