wp_referer_field()
Display or retrieve a hidden input field for form with the current page URI value (referer).
The referer link is the current Request URI — $_SERVER['REQUEST_URI']
. The input name is _wp_http_referer
, in case you wanted to check manually:
<input type="hidden" name="_wp_http_referer" value="/current-page" />
No Hooks.
Return
String
. Referer field HTML markup.
Usage
wp_referer_field( $display );
- $display(true|false)
- Whether to echo or return the referer field.
Default: true
Examples
#1 Redirect back
// has operation if ( $doaction ) { // do something } // no operation, redirect user back elseif ( ! empty($_REQUEST['_wp_http_referer']) ) { wp_save_redirect( $_REQUEST['_wp_http_referer'] ); exit; }
#2 Let's add the hidden _wp_http_referer field and check it.
Let's add a hidden _wp_http_referer field to our form and then check this field to make sure that the request came from the page we need. Suppose that the page with the form has /my-page
URL.
Code of the form:
<form action="/check.php" method="post"> ... other fields ... <?php wp_referer_field() ?> ... submit button ... </form>
wp_referer_field() will print:
<input type="hidden" name="_wp_http_referer" value="/my-page" />
Code of the check.php:
if( $_POST['_wp_http_referer'] === '/my-page' ){ // Check passed! Handle data here. } else { // Check failed! }
Changelog
Since 2.0.4 | Introduced. |
wp_referer_field() wp referer field code WP 6.7.1
function wp_referer_field( $display = true ) { $request_url = remove_query_arg( '_wp_http_referer' ); $referer_field = '<input type="hidden" name="_wp_http_referer" value="' . esc_url( $request_url ) . '" />'; if ( $display ) { echo $referer_field; } return $referer_field; }