How to get URL of current page displayed in WordPress?

There are several ways to get the URL of the current page displayed in WordPress:

  1. Using the get_permalink Function: This is the simplest and most straightforward method to get the URL of the current page. You can use the get_permalink function in your WordPress theme template files, like this:
scss
$current_url = get_permalink();
  1. Using the esc_url and home_url Functions: Another method is to use the esc_url and home_url functions in WordPress. This method is useful if you need to add a URL to an HTML link, for example:
less
$current_url = esc_url( home_url( add_query_arg( array(), $wp->request ) ) );
  1. Using the $_SERVER Variable: You can also use the $_SERVER variable in PHP to get the URL of the current page. Here’s an example:
php
$current_url = ( isset( $_SERVER['HTTPS'] ) ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  1. Using the $wp Global Variable: Finally, you can use the $wp global variable in WordPress to get the URL of the current page. Here’s an example:
bash
$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );

These are some of the most common methods to get the URL of the current page in WordPress. You can use the method that best fits your needs.

It’s important to note that the URL of the current page is a dynamic value that can change depending on the page being viewed. This means that the URL will be different when a user visits your home page, a single post, a category archive, or any other type of page on your WordPress site.

When working with URLs in WordPress, it’s also important to make sure that the URLs you use are properly formatted and secure. This can be done by using the WordPress functions mentioned above, which automatically handle formatting and security concerns for you.

In addition to getting the URL of the current page, you can also use these techniques to get the URL of other pages on your site, such as your home page, category archives, and custom post type archives. You can use the URL of the current page in various ways, such as in links, in redirects, and in content.

In conclusion, getting the URL of the current page in WordPress is a common task that can be easily accomplished using the methods described above. Whether you need to add a link to the current page, redirect the user to another page, or simply display the URL for reference, these techniques will help you get the job done quickly and easily.