在我的博客页面上,我有两个默认的wordpress搜索表单,一个在标题中,应该搜索所有内容,另一个在侧边栏中,应该只搜索帖子。
我设法通过pre_get_posts更改为查询以满足我的需求,但它对两种搜索形式都进行了更改
function exclude_pages($query) {
if ($query->is_home() && $query->is_main_query() && !is_admin() ) {
$query->set('post_type', 'post');
}
}
add_action('pre_get_posts', 'exclude_pages');
我如何指定该函数只更改侧边栏中搜索表单的查询?
在其中一个搜索表单中添加一个隐藏字段,然后检查是否在pre_get_posts
中为其设置了值。
在侧边栏表单中添加:
<input type="hidden" name="posts-only" value="1" />
然后更改:
if ($query->is_home() && $query->is_main_query() && !is_admin() ) {
$query->set('post_type', 'post');
}
收件人:
// Check if posts only value has been set and equal to 1. Return if not.
if ( ! isset( $_GET['posts-only'] ) || 1 !== $_GET['posts-only'] ) {
return false;
}
if ( $query->is_home() && $query->is_main_query() && ! is_admin() ) {
$query->set( 'post_type', 'post') ;
}