2
votes

Is there any function that gets the URL of the current page I am viewing on my Wordpress blog? 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(). I need one that gets index / category / ect' pages too.

Thank you,

Hatzil.

2
get_permalink without any arguments should do the trickHobo
I didn't know this function exists. But still, it doesn't work on the index page for example (shows a post link, I think the last post as mentioned on the Wordpress documentation website, and doesn't work on category pages too I think).user3728949

2 Answers

6
votes

Here is a handy snippet with which you can easily get current URL on your WordPress website. It doesn’t matter if you need it on single post, page, home, category, tag, custom post type or any other WordPress template.

You can use this piece of code inside any template on your WordPress website:

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

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. However, there is a hook there, so it brings some flexibility. And standardization.