wp_get_referer()
Gets the referer link (referer URL) only if it is an internal URL - the URL of the current site.
Will return false if the referer is equal to the current page.
This function is a combination of two functions: wp_get_raw_referer() and wp_validate_redirect().
The referer link (URL) is the URL of the page from which the user came to the current page.
No Hooks.
Returns
String|false
. Referer URL or false.
Usage
$referer = wp_get_referer();
Examples
#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.
#2 What the function outputs
echo wp_get_referer(); // /some-page?foo=bar
Changelog
Since 2.0.4 | Introduced. |
wp_get_referer() wp get referer code WP 6.8.1
function wp_get_referer() { // Return early if called before wp_validate_redirect() is defined. 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; }