How to Get Current URL in WordPress (PHP Snippet)

Developing a WordPress theme or a custom function for your WordPress site? Getting a page or post’s current URL can be useful no matter what you’re creating. In this quick guide I’ll go over how to get the current URL in WordPress with PHP.

Get Current Page URL Using PHP

This PHP code snippet will get the current page URL of any WordPress page on your site. No matter if it’s a single post, page, archive, or category this snippet will work for grabbing any page URLs on your site.

global $wp;
$current_url = home_url( add_query_arg( array(), $wp->request ) );
echo $current_url;

There are plenty of other methods to get the current URL in WordPress as well.

Get Current WordPress Slug Using PHP

If you just want to the the current page/post’s slug you can use this PHP function below. No matter if it’s archive page or a single post this code will work with any type of page in WordPress.

global $wp;
$current_slug = add_query_arg( array(), $wp->request );
echo $current_slug;

The WordPress slug is the text after your domain name. For example the slug would be “about”. The WordPress slug is useful for uniquely identifying content in a readable way.

Get Current Page URL with Query String using PHP

If you want the full URL of your page with the query string included you can use the snippet below.

The query string is typically something like ?page=2 after your URL. If you want to use query vars in your PHP functions you can use WordPress’ get_query_var function.

$url_parts = parse_url( home_url() );
$current_url_with_query_string = $url_parts['scheme'] . "://" . $url_parts['host'] . add_query_arg( NULL, NULL );
echo $current_url_with_query_string;

In summary, understanding how to retrieve the current URL in WordPress using a PHP snippet unlocks a world of possibilities for customization and optimization. With the step-by-step instructions and knowledge you’ve gained from this blog post, you can confidently use this technique and take your WordPress development skills to the next level.

Have more questions about WordPress development? Ask them below in the comments.

Andy Feliciotti

Andy Feliciotti

Andy has been a full time WordPress developer for over 10 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way. Found this article helpful? Buy Me A Coffee

One Response

Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress Tips Monthly
Get the latest from SmartWP to your inbox.