因此,我试图在博客页面上创建一个搜索表单,以便它只搜索包含" blog“类别的文章--这是我使用的搜索表单代码:
<form method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="hidden" name="cat" id="blog" value="7" />
<input type="text" value="<?php echo get_search_query(); ?>" name="s" />
<input type="submit" value="Search" />
</form> 这是search.php代码:
<?php
/**
* The template for displaying search results pages
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
*
* @package Scrap
*/
get_header();
?>
<main id="primary" class="site-main">
<?php
$s=get_search_query();
$args = array(
's' =>$s
);
// The Query
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
_e("<h2 style='font-weight:bold;color:#000'>Search Results for: ".get_query_var('s')."</h2>");
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
}
}else{
?>
<h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
<div class="alert alert-info">
<p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
</div>
<?php } ?>
</main><!-- #main -->
<?php
// get_sidebar();
get_footer();当搜索查询时,url会加载,就好像它仅限于类别:https://www.scraperapi.com/?cat=7&s=proxies,但是它仍然显示来自类别之外的页面,并且它没有加载与搜索查询匹配的所有博客文章。搜索表单位于https://www.scraperapi.com/blog/,但它是显示的:隐藏在顶部称为“博客搜索”的div中。
非常感谢您提前提供的任何帮助!
发布于 2021-12-07 21:20:24
尝试用变量获取query_variable " cat“,并将cat变量也包含在WP_Query中。在这方面也有一些好的信息这里。目前,$args只包含变量$s的搜索项。
以下是改编后的$args
$cat = get_query_var('cat');
$s=get_search_query();
$args = array(
's' => $s,
'cat' => $cat
);
//etc..或者,也可以修改$wp_query全局变量。这可以通过设置tax_query的$wp_query来完成。
global $wp_query;
$tax_query[] = array(
array(
'taxonomy' => 'cat',
'field' => 'id',
'terms' => $cat,
)
);
$wp_query->set( 'tax_query', $tax_query );发布于 2021-12-07 21:20:49
您可以通过pre_get_posts钩子过滤器拦截和修改查询。
<?php
//function.php
add_filter( 'pre_get_posts', 'wpso_70266736' );
if ( ! function_exists( 'wpso_70266736' ) ) {
function wpso_70266736( $query ) {
if( $query->is_search() && $query->is_main_query() && !isset( $_GET['category'] ) ) {
$query->set_404();
status_header( 404 );
get_template_part( 404 );
exit();
};
};
};https://stackoverflow.com/questions/70266736
复制相似问题