5

Get the URL of the Current Displayed Page

 2 years ago
source link: https://pineco.de/snippets/get-the-url-of-the-current-displayed-page/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Get the URL of the Current Displayed Page

In WordPress, depending on what URL you want to query, there are many methods. For example, we usually access the URL with the get_permalink() function, but this solution only works for single views of any post type.

Let’s see how we can get the current URL in WordPress:


global $wp;
echo esc_url(home_url($wp->request));

Using $wp global, we can access our request, which we can pass to the home_url() function to convert to a full URL. The $wp->request includes just the path URL like /about/us.

If you want to get an URL with query parameters you should also use the add_query_arg() function like so:


global $wp;
echo esc_url(home_url(add_query_arg([$_GET]), $wp->request));

As you see, we also used the esc_url() function to escape our URLs before displaying them.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK