Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created July 21, 2016 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/653704cfb6dacf6022432a325ef0ff10 to your computer and use it in GitHub Desktop.
Save tommcfarlin/653704cfb6dacf6022432a325ef0ff10 to your computer and use it in GitHub Desktop.
[WordPress] Maintain WordPress Query String Variables After a Redirect
<?php
/**
* Redirect to the page from which we came (which should always be the
* admin page. If the referred isn't set, then we redirect the user to
* the login page.
*
* @access private
*/
private function redirect() {
// To make the Coding Standards happy, we have to initialize this.
if ( ! isset( $_POST['_wp_http_referer'] ) ) { // Input var okay.
$_POST['_wp_http_referer'] = wp_login_url();
}
// Sanitize the value of the $_POST collection for the Coding Standards.
$url = sanitize_text_field(
wp_unslash( $_POST['_wp_http_referer'] ) // Input var okay.
);
// Finally, redirect back to the admin page.
wp_safe_redirect( urldecode( $url ) );
exit;
}
<?php
/**
* Determines if the current user has permissions to save and, if so, saves
* each option.
*/
public function save() {
// Determine if the user has the ability to save the options.
if ( ! $this->can_save() ) {
$this->messenger->add_error_message(
'You do not have permission for this operation.'
);
} else {
$this->save_options()
}
// Redirect back to the administration page.
$this->redirect();
}
<?php
/**
* Add an error message to the error message collection. If the incoming
* message is an array, then an unordered list of errors will be rendered.
*
* @param array $message The message to add to the collection of errors.
*/
public function add_error_message( $message ) {
// Add the message to the array of errors and then update the option.
$this->errors[] = esc_html( $message );
$this->serialize_errors();
}
<?php
/**
* Saves the collection of error messages to the database.
*
* @access private
*/
private function serialize_errors() {
update_option( 'acme-error-messages', $this->errors );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment