Created
March 1, 2025 18:08
-
-
Save pattihis/040da6e9bf52418e37f335fbcf615f66 to your computer and use it in GitHub Desktop.
A replacement function for WordPress's get_query_var() that addresses the issue of query variables not being set on some servers, by parsing the globals directly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get the query variable even if the server rewrite rules do not support it. | |
* This is a workaround for the issue where the query vars are not set in the globals. | |
* | |
* @global WP_Query $wp_query WordPress Query object. | |
* | |
* @param string $query_var The variable key to retrieve. | |
* @param mixed $default_value Optional. Value to return if the query variable is not set. | |
* Default empty string. | |
* @return mixed Contents of the query variable. | |
*/ | |
function safe_get_query_var( $query_var, $default_value = '' ) { | |
global $wp_query; | |
// Check $wp_query->query_vars first | |
if ( isset( $wp_query->query_vars[ $query_var ] ) ) { | |
return $wp_query->query_vars[ $query_var ]; | |
} | |
// Fallback to $_GET | |
if ( isset( $_GET[ $query_var ] ) ) { | |
return sanitize_text_field( wp_unslash( $_GET[ $query_var ] ) ); | |
} | |
// Fallback to $_POST | |
if ( isset( $_POST[ $query_var ] ) ) { | |
return sanitize_text_field( wp_unslash( $_POST[ $query_var ] ) ); | |
} | |
// Parse REQUEST_URI as a last resort | |
static $cached = null; | |
if ( $cached === null ) { | |
$request = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_url( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; | |
$parts = explode( '?', $request, 2 ); | |
$cached = []; | |
if ( isset( $parts[1] ) ) { | |
$query_pairs = explode( '&', $parts[1] ); | |
foreach ( $query_pairs as $pair ) { | |
list($key, $value) = array_pad( explode( '=', $pair, 2 ), 2, null ); | |
$cached[ urldecode( $key ) ] = urldecode( $value ); | |
} | |
} | |
} | |
// Return the variable if found in the parsed query string | |
if ( isset( $cached[ $query_var ] ) ) { | |
return sanitize_text_field( wp_unslash( $cached[ $query_var ] ) ); | |
} | |
// Return the default value if the variable is not found | |
return $default_value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment