wc_query_string_form_fields()
Outputs hidden form inputs for each query string variable.
No Hooks.
Returns
String.
Usage
wc_query_string_form_fields( $values, $exclude, $current_key, $return );
- $values(string|array)
- Name value pairs, or a URL to parse.
Default:null - $exclude(array)
- Keys to exclude.
Default:array() - $current_key(string)
- Current key we are outputting.
Default:'' - $return(true|false)
- Whether to return.
Default:false
Changelog
| Since 3.0.0 | Introduced. |
wc_query_string_form_fields() wc query string form fields code WC 10.9.4
function wc_query_string_form_fields( $values = null, $exclude = array(), $current_key = '', $return = false ) {
if ( is_null( $values ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$values = $_GET;
} elseif ( is_string( $values ) ) {
$url_parts = wp_parse_url( $values );
$values = array();
if ( ! empty( $url_parts['query'] ) ) {
// This is to preserve full-stops, pluses and spaces in the query string when ran through parse_str.
$replace_chars = array(
'.' => '{dot}',
'+' => '{plus}',
);
$query_string = str_replace( array_keys( $replace_chars ), array_values( $replace_chars ), $url_parts['query'] );
// Parse the string.
parse_str( $query_string, $parsed_query_string );
// Convert the full-stops, pluses and spaces back in all scalar values (any depth).
array_walk_recursive(
$parsed_query_string,
function ( &$value ) use ( $replace_chars ) {
$value = str_replace( array_values( $replace_chars ), array_keys( $replace_chars ), $value );
}
);
// Restore placeholders in keys at every depth, then add to values array.
$restore_keys = function ( $items ) use ( &$restore_keys, $replace_chars ) {
$out = array();
foreach ( $items as $key => $value ) {
$key = str_replace( array_values( $replace_chars ), array_keys( $replace_chars ), $key );
$out[ $key ] = is_array( $value ) ? $restore_keys( $value ) : $value;
}
return $out;
};
$values = $restore_keys( $parsed_query_string );
}
}
$html = '';
foreach ( $values as $key => $value ) {
if ( in_array( $key, $exclude, true ) ) {
continue;
}
if ( $current_key ) {
$key = $current_key . '[' . $key . ']';
}
if ( is_array( $value ) ) {
$html .= wc_query_string_form_fields( $value, $exclude, $key, true );
} else {
$html .= '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( wp_unslash( $value ) ) . '" />';
}
}
if ( $return ) {
return $html;
}
echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}