wp_get_referer()WP 2.0.4

Retrieve referer from '_wp_http_referer' or HTTP referer.

If it's the same as the current request URL, will return false.

1 time — 0.001678 sec (very slow) | 50000 times — 2.26 sec (fast) | PHP 7.0.32, WP 5.1.1

No Hooks.

Return

String|false. Referer URL on success, false on failure.

Usage

wp_get_referer();

Examples

0

#1 Display the "Go Back" link

Suppose we in the admin panel of the site followed a link to our plugin page and we need to display a link "Back" on this page, among other things

A solution to such a problem might look like this:

<?php

$return_url = wp_get_referer();

if( $return_url ){
	?>
	<p><a class="button" href="<?php echo esc_url( $return_url ); ?>">Return</a></p>
	<?php
}

Here it should be noted that this link will be displayed only if the page is accessed from another page. But if on the same page, for example, you refresh the form data, the referrer will be equal to the current URL, and the "Back" link will not be displayed. In this case, in order to make the "Go Back" link work as needed, it needs to be saved somewhere when the page is first visited (e.g. in transient options) and taken from there when the URL is copied.

Changelog

Since 2.0.4 Introduced.

wp_get_referer() code WP 6.1.1

function wp_get_referer() {
	if ( ! function_exists( 'wp_validate_redirect' ) ) {
		return false;
	}

	$ref = wp_get_raw_referer();

	if ( $ref && wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref && home_url() . wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref ) {
		return wp_validate_redirect( $ref, false );
	}

	return false;
}