When using functions with WordPress, you’ll sometimes need to get the URL of the page you’re currently on.
In this article, you’ll learn how to get the URL of the current page in WordPress.
Why Getting Page’s URL
There are many reasons to get a page’s link, and it all depends on what the function is trying to achieve.
For example, you can display the page’s URL and create a copy to clipboard button.
Other popular functions will need the current URL to display related posts at the bottom of every blog post.
Knowing how to get the current page URL is necessary and will become handy at some point or another.
Whatever the reason, getting the current page URL is a simple task, and the next section will teach you exactly how.
Get the Current Page’s URL in WordPress
The first couple of snippets in this article will work with any WordPress template file. The second part will be template-specific.
The codes will get the URL for any page type like single post, single page, the home page, taxonomies templates, search templates, custom post types, etc.
Using a child theme when working with WordPress core files is highly recommended. Please create a child theme if you don’t already have one before moving forward.
Use the code below to get the current page URL:
global $wp; $current_url = home_url( add_query_arg( array(), $wp->request ) );
To get the last slug only of the current URL without the base part, use this:
global $wp; $current_url = add_query_arg( array(), $wp->request );
For example, if your website is
https://pluginsforwp.com/post-name the code above will return just the
Get current URL in specific templates
When working with WordPress templates, you can use the specific code snippets below to utilize the template and get the current URL of the page.
The snippets are very similar to each other. Make sure to replace the second line of the code based on the template you’re using.
$queried_id = get_queried_object_id(); //SECOND LINE GOES HERE
For single.php or page.php, replace the second line of the code with:
$current_url = get_permalink( $queried_id );
If you would like to get the taxonomy URLs like category or tag, replace the second line of the code with:
$current_url = get_term_link( $queried_id );
Last, for the archive page URL, replace the second line of the code with:
$current_url = get_author_posts_url( $queried_id );
To get the home page URL (it doesn’t matter which page you’re on), use the code snippet below (you don’t need the first line above):
$current_url = home_url( '/' );
In this article, you learned how to get the URL of the current page in WordPress.
Leave us a comment and tell us which one of the codes you used above.