【问题标题】:Wordpress how to use a second form that only searches for posts?Wordpress 如何使用仅搜索帖子的第二种形式?
【发布时间】:2021-08-04 22:45:38
【问题描述】:

我的 wordpress 网站上有两个表单,search.blade.phpblog-search.blade.php

search.blade.php 位于网站标题中,搜索所有内容类型。

blog-search.blade.php 仅用于搜索帖子类型。

我正在使用以下代码让它只搜索博客文章:

    function searchfilter($query) {
 
    if ($query->is_search && !is_admin() ) {
        $query->set('post_type', 'post');
    }
 
return $query;
}
 
add_filter('pre_get_posts','searchfilter');

可以理解,这适用于 search.blade.php 和 blog-search.blade.php,但我只希望它适用于 blog-search。

我认为如果我添加一个条件来检查仅存在于博客搜索中的隐藏输入的值,我可以让它工作,但我不知道该怎么做。

这是我的 blog-search.blade.php 代码:

<form action="{{ get_bloginfo('url') }}" method="GET" class="blog-search-form">
    <input type="search" name="s" placeholder="Search the blog...">
    <input type="hidden" name="search-type" value="normal" />
    <span class="icon-search"></span>
</form>

有没有办法实现类似的东西:

 function searchfilter($query) {
 
    if ($query->is_search && !is_admin() && INPUT TYPE == HIDDEN ) {
        $query->set('post_type', 'post');
    }
    ...

所以只有博客搜索搜索帖子,而我的主要搜索照常工作?我尝试了implementing this,但没有成功,所以我认为条件可以提供帮助。

search.blade.php,以防万一:

<form action="{{ get_bloginfo('url') }}" method="GET" class="search-form">
    <input type="search" name="s" placeholder="Search the site">
</form>

【问题讨论】:

    标签: php wordpress forms query-string query-variables


    【解决方案1】:

    您可以通过多种方式进行设置。我个人总是使用 ajax 方法来查询数据库,但是如果您想使用 query_vars 方法,因为您已经在考虑它并在您的问题中提出它,那么您可以这样做:

    所以这将是你的 html 表单:

    <form method="GET">
        <input type="search" name="s" placeholder="Search the blog...">
        <input type="hidden" name="onlyblog" id="onlyblog" value="yes" />
        <span class="icon-search"></span>
        <button type="submit">Search</button>
    </form>
    

    然后在php 方面,您的条件检查将像这样检查onlyblog 值:

    function searchfilter($query) {
    
    $query_type = isset($_GET['onlyblog']) ? sanitize_text_field($_GET['onlyblog']) : "";
     
        if ($query->is_search && !is_admin() && !empty($query_type) && 'yes' == $query_type) {
            $query->set('post_type', 'post');
        }
     
    return $query;
    }
    

    如果你能让它工作,请告诉我!

    【讨论】:

    • 抱歉耽搁了。我能够让它工作 - 谢谢!奇怪的是,在我的网站的一个版本上存在问题 - 当我在开发环境中尝试您的代码时,它运行良好。
    猜你喜欢
    • 2011-05-11
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    相关资源
    最近更新 更多