If you’re using functions to run codes on your website use the snippets below to get the URL of the current page you’re on in WordPress.
The first couple of snippets in this article will work with any WordPress template file while 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 while using Specific WordPress 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 current single.php or page.php, replace the second line of the code with:
$current_url = get_permalink( $queried_id );
For current taxonomy URLs like category or tag, replace the second line of the code with:
$current_url = get_term_link( $queried_id );
For the current 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.
Take the codes for a spin and let us know which one you chose to use and for what purpose.