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.

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

There are plenty of rea

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.

<?php
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 yoursite.com/about/ 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.

<?php
$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;

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.

Leave a Reply

Your email address will not be published.

WordPress Tips Monthly

Get the latest from SmartWP to your inbox.