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 why to get a page’s link and it all depends on what the function is trying to achieve.
For example, if you’d like to display a page’s path, use one of the code snippets below to retrieve it.
Other functions will need to get the URL of pages to display a related posts section below the blog post.
Whatever the reason may be, getting the URL of the current page 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, categories & tags templates, search templates, custom post types and etc.
It’s highly recommended to use a child theme when working with WordPress core files. If you don’t have a child theme currently active, read our article on how to create a child theme.
The code below will get you the full 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 for 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 working with.
$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 );
If you would like to get the home page URL (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 you’re on.
Leave us a comment and let us know which one of the codes above you used.