Get the current page URL in WordPress – The WordPress solution

Get current page URL in WordPress

You might need the current page URL whenever a page is opened in the browser. With a simple code, we can get the current page URL using WordPress hooks and native functions. In this article, we will see how to get the current page URL in WordPress.

The simplest method:

To get single pages:

<?php
	get_permalink( get_the_ID() );
?>

Such a case usually occurs when you are developing a plugin or you need the functionality on a specific page. For example, on the “about us” page if you need different functionality from other pages, you can get the URL using the following snippet:

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

The above snippet will return the current page URL in WordPress.

You can write the above code in the functions.php file or in your plugin or template file.

Get the URL for a single post:

To get URL of single post, add the following snippet in the single.php or page.php of the loaded theme file:

<?php
	$obj_id = get_queried_object_id();
	$current_url = get_permalink( $obj_id );
?>

Get page slug

If you want to get the slug of the loaded page, use the following snippet:

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

The generic PHP method using SERVER variables:

One of the most compatible solutions in PHP is the following snippet. It uses the SERVER variables:

<?php
	function current_location() {
	    if (isset($_SERVER['HTTPS']) &&
	        ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
	        isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
	        $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
	        $protocol = 'https://';
	    } else {
	        $protocol = 'http://';
	    }
	    return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
	}

	echo current_location();
?>

In the next article, you will see how to also fetch the current page URL in core PHP.

Related Posts