简体   繁体   English

如何使用wordpress(包括索引和类别页面)获取当前URL

[英]How to get the current URL using wordpress (including index and category pages)

Is there any function that gets the URL of the current page I am viewing on my Wordpress blog? 是否有任何功能可以获取我在Wordpress博客上正在查看的当前页面的URL? All that I found was Boolean functions that check if the page is the homepage/category/single post/etc' and now the exact page that is viewed. 我发现的只是布尔函数,它们检查页面是否是主页/类别/单篇文章/等,以及现在所查看的确切页面。

Edit: There is a function that gets posts URL - get_permalink(). 编辑:有一个获取帖子URL的函数-get_permalink()。 I need one that gets index / category / ect' pages too. 我也需要获取索引/类别/等页面的页面。

Thank you, 谢谢,

Hatzil. Hatzil。

Here is a handy snippet with which you can easily get current URL on your WordPress website. 这是一个方便的代码段,您可以轻松地在WordPress网站上获取当前URL。 It doesn't matter if you need it on single post, page, home, category, tag, custom post type or any other WordPress template. 无论您是在单个帖子,页面,首页,类别,标签,自定义帖子类型还是任何其他WordPress模板上使用它都没关系。

You can use this piece of code inside any template on your WordPress website: 您可以在WordPress网站上的任何模板中使用以下代码:

global $wp;
$current_url = home_url(add_query_arg(array(),$wp->request));

Here is a snippet from my code: 这是我的代码片段:

/**
 * There is no method of getting the current URL in WordPress.
 * Various snippets published on the Web use a combination of home_url and add_query_arg.
 * However, none of them work when WordPress is installed in a subfolder.
 * The method below looks valid. There is a theoretical chance of HTTP_HOST tampered, etc.
 * However, the same line of code is used by the WordPress core, for example in
 * @see wp_admin_canonical_url
 * so we are going to use it, too
 * *
 * Note that #hash is always lost because it's a client-side parameter.
 * We might add it using a JavaScript call.
 */
$current_url  = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );

The set_url_scheme looks overkill: it's very easy to get the scheme without it. set_url_scheme看起来有点过大:没有它,很容易获得该方案。 However, there is a hook there, so it brings some flexibility. 但是,那里有一个挂钩,因此带来了一定的灵活性。 And standardization. 和标准化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM