WordPress: Get Current URL and Slug
Another essential tool for your WordPress development toolbox is getting the URL of the current page. This sounds simple but can be tricky depending on which page or type of page is being displayed. So to help, here is a simple technique to get the current URL for any single post, archive view, custom template, or literally any page served by WordPress.
Get current URL in WordPress
To get the current URL of any WP-generated web page (e.g., single post, archive, etc.), add the following code to theme functions file or plugin:
global $wp;
$current_url = home_url(add_query_arg(array(), $wp->request));
That’s all there is to it, easy peasy.
Get current permalink slug
Another, related technique is getting the “slug” part of the permalink/URL. For example, if the full URL is https://example.com/my-post/
, the slug would be my-post
. Here is how to get that information for any page:
global $wp;
$current_slug = add_query_arg(array(), $wp->request);
Note that in some cases, like on the home page, the slug may be empty.
Alternate ways of doing it
The above technique is an “all-in-one” approach that can get the URL for any WordPress-generated web page. There also are some built-in WP functions that can help with specific types of page views.
// home page
$current_url = home_url('/');
// any single post or page
$object_id = get_queried_object_id();
$current_url = get_permalink($object_id);
// taxonomy term archive
$object_id = get_queried_object_id();
$current_url = get_term_link($object_id);
// author archive
$object_id = get_queried_object_id();
$current_url = get_author_posts_url($object_id);
Use whichever technique makes the most sense for your project! :)