在现有查询字符串上添加搜索字符串


WordPress / PHP: Add search string onto existing query string

在wordpress主题中,我设置了一些基于自定义分类法的搜索过滤器,它将使用URL结构查询帖子,如:

http://myblog.com/?taxonomy1=term1+term2&taxonomy2=term3+term4

除了这些过滤器之外,我想集成一个文本搜索,但不知道如何将搜索查询(例如?s=mysearchhere)附加到现有的分类法查询上。总而言之,提交时,我希望表单指向一个url它由两个字符串组成:

" http://myblog.com/?taxonomy1=term1 + term2& taxonomy2 = term3 + term4& s = mysearchhere"

到目前为止,我已经尝试使用以下函数生成搜索表单:

 function remove_querystring_var($url, $key) { 
        $url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&'); 
        $url = substr($url, 0, -1); 
        return $url; 
    }
function apl_search_form($echo = true) {
    do_action( 'get_search_form' );
    $search_form_template = locate_template('searchform.php');
    if ( '' != $search_form_template ) {
        require($search_form_template);
        return;
    }
    $url = $_SERVER["REQUEST_URI"]; 
    $action = remove_querystring_var($url,'s');

    $form = '<form role="search" method="get" id="searchform" action="' . $action . '" >
    <div><label class="screen-reader-text" for="s">' . __('Search for:') . '</label>
    <input type="text" value="' . get_search_query() . '" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" />
    </div>
    </form>';
    if ( $echo )
        echo apply_filters('get_search_form', $form);
    else
        return apply_filters('get_search_form', $form);
}

这似乎不起作用。这个问题比我想象的要复杂吗?还是我走对了路?有人知道一种直接的编码方式吗?

多谢谢!

您可以在URL后面加上&搜索词,如下所示

&s=mysearchhere

主URL后的第一个数据位以'?’之后,对于每一个额外的数据位,它总是附加一个'&'。你永远不需要"&?"’在一起。

检索
$query = $_GET['s'];

我刚刚遇到了这个问题,并找到了一个解决方案。

为了澄清问题,假设您有一个搜索表单:

<form method="get" action="http://myblog.com/?taxonomy1=term1">
<input type="text" name="keyword" />
</form>

注意键/值taxonomy1=term1是操作URL的一部分。

现在假设用户搜索"asdf"。这就是我天真地期望的URL:

http://myblog.com/?taxonomy1=term1&keyword=asdf

下面是URL的实际内容:

http://myblog.com/?keyword=asdf

URL中键/值为"taxonomy1=term"的部分被剥离。

"添加查询字符串返回"的方法是在表单中添加一个隐藏的输入字段:

<input type="hidden" name="taxonomy1" value="term" />

要在查询字符串中添加更多参数,可以添加任意数量的隐藏类型输入,如下所示:

<input type="hidden" name="taxonomy1" value="term" />
<input type="hidden" name="taxonomy2" value="term3" />

我刚刚验证了这一点,所以我确定它是有效的!