返回 WordPress 中的当前 URL

B4b*_*4j1 5 php url wordpress return-value

我正在尝试在 WordPress 中实现规范和 hreflang 标签,但无法检索访问页面的当前 URL。

我试过 :

 <?php echo site_url(); ?>
Run Code Online (Sandbox Code Playgroud)

但它返回https://www.example.com而不是https://www.example.com/current-page1

小智 8

万一其他人需要这个。下面的代码应该获取包含参数的确切 URL。

home_url($_SERVER['REQUEST_URI']);
Run Code Online (Sandbox Code Playgroud)

您可以根据您的用例回显或返回它。例如

echo home_url($_SERVER['REQUEST_URI']);
Run Code Online (Sandbox Code Playgroud)

或者

return home_url($_SERVER['REQUEST_URI']);
Run Code Online (Sandbox Code Playgroud)

  • 它不适用于安装在子文件夹中的 wp。它使子文件夹加倍 (2认同)

Fri*_*its 7

site_url()函数返回实际的网站根 URL。根据您调用 URL 的位置,您可以尝试get_the_permalink(),但更可靠的方法是使用该$wp->request方法。像这样:

global $wp;
echo home_url( $wp->request )
Run Code Online (Sandbox Code Playgroud)

这个函数的主要问题是 URL 参数被遗漏了,所以如果你的链接是这样的:http://example.com/test/?myparam=1它只会返回http://example.com/test/