使用Wordpress在URL中保留Echo变量的格式


Preserve Format of Echo variable in URL with Wordpress

我正在wordpress中的模板中添加一个函数,将变量($location)链接到该位置的所有事件的搜索。这基本上包括创建一个指向网站搜索结果的链接,并将$location作为搜索字符串。然而,我遇到的问题是,尽管在URL之外,我可以调用$location变量,并且它保留了位置名称中的空格:

NRS Arena

当我在url中使用变量时,它显示为

NRSArena

我的搜索词。我真的需要这个术语格式化为

NRS+竞技场或NRS%20Rena

以便在搜索字符串中有效使用。

这是我的代码:

$html .= html( 'a', array( 'href' => esc_url( get_site_url() . '/?st=event&ls=' . $location . '&location='), 'target' => '_blank' ), $location));

所以对于

$location=NRS Arena

我希望它像这样输出HTML:

<a target="_blank" href="http://www.mysiteurl.com/?st=event&ls=NRS+Arena&location=">NRS Arena</a>

或者甚至NRS和Arena之间的%20也可以,而不是+

相反,它正在输出:

<a target="_blank" href="http://www.mysiteurl.com/?st=event&ls=NRSArena&location=">NRS Arena</a>

通过删除URL中单词之间的空格,显然网站搜索是行不通的。我不明白为什么在URL之外使用$location可以保留空间,但在URL内部却不能。

如有任何帮助,我们将不胜感激。

您有两个选项:

  1. 使用rawurlencode-返回%20

$html.=html('a',array('href'=>esc_url(get_site_url().'/?st=事件&ls='。rawurlencode($location)。'&location='),'target'=>'_blank'),$location));

  1. 使用url_encode-returns+

$html.=html('a',array('href'=>esc_url(get_site_url().'/?st=事件&ls='。url_encode($location)。'&location='),'target'=>'_blank'),$location));