Getting the referring URL in WordPress using wp_get_referer

The wp_get_referer function in WordPress retrieves the referring page from the HTTP request. This can be useful for tracking where a user came from before landing on a specific page within a WordPress site. It can also be used to customize the user experience based on the referring page.

Parameters and Return Value of wp_get_referer Function

The wp_get_referer function does not accept any parameters. It simply retrieves the referer URL from the HTTP header of the current request.

When the function is successful, it returns the referer URL as a string. However, if it fails to retrieve the referer URL, it returns false.


Examples

How to get the referring URL using wp_get_referer

Code snippet:

$referer = wp_get_referer();
if ( $referer ) {
 echo 'The referring URL is: ' . $referer;
} else {
 echo 'No referring URL found.';
}

This code snippet uses wp_get_referer() to retrieve the referring URL. It then uses an if statement to check if a referring URL exists, and if so, it echoes the URL. If no referring URL is found, it echoes a message indicating that no referring URL was found.

How to redirect to the referring URL using wp_get_referer

Code snippet:

$referer = wp_get_referer();
if ( $referer ) {
 wp_redirect( $referer );
 exit;
} else {
 // Redirect to a default URL
 wp_redirect( home_url() );
 exit;
}

This code snippet uses wp_get_referer() to retrieve the referring URL. It then uses an if statement to check if a referring URL exists. If a referring URL is found, it uses wp_redirect() to redirect to that URL and then exits the script. If no referring URL is found, it redirects to a default URL (in this case, the home URL) and then exits the script.

How to perform a specific action based on the referring URL using wp_get_referer

Code snippet:

$referer = wp_get_referer();
if ( $referer && strpos( $referer, 'example.com' ) !== false ) {
 // Perform a specific action for referring URLs containing 'example.com'
 // ...
} else {
 // Perform a default action
 // ...
}

This code snippet uses wp_get_referer() to retrieve the referring URL. It then uses an if statement to check if a referring URL exists and if it contains ‘example.com’. If the condition is met, it performs a specific action for referring URLs containing ‘example.com’. If the condition is not met, it performs a default action.

Conclusion

In conclusion, the wp_get_referer function is a useful tool for retrieving the referring URL in WordPress. It provides a simple and reliable way to access this information, which can be valuable for tracking user behavior and improving website functionality. By understanding how to properly utilize this function, developers can enhance the user experience and make more informed decisions about their WordPress sites.

Related WordPress Functions