add_query_arg

Retrieves a modified URL query string.

Description

(string) add_query_arg(); 

You can rebuild the URL and append query variables to the URL query by using this function. There are two ways to use this function; either a single key and value, or an associative array.

Using a single key and value:

Using an associative array:

key1 => value1, key2 => value2,

Omitting the URL from either use results in the current URL being used (the value of $_SERVER['REQUEST_URI']).

Values are expected to be encoded appropriately with urlencode() or rawurlencode().

Setting any query variable's value to boolean false removes the key (see remove_query_arg()).

Important: The return value of add_query_arg() is not escaped by default. Output should be late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting (XSS) attacks.

Returns (string)

New URL query string (unescaped).


Usage

  1. if ( !function_exists( 'add_query_arg' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4.  
  5. // NOTICE! Understand what this does before running. 
  6. $result = add_query_arg(); 
  7.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/functions.php  
  1. function add_query_arg() { 
  2. $args = func_get_args(); 
  3. if ( is_array( $args[0] ) ) { 
  4. if ( count( $args ) < 2 || false === $args[1] ) 
  5. $uri = $_SERVER['REQUEST_URI']; 
  6. else 
  7. $uri = $args[1]; 
  8. } else { 
  9. if ( count( $args ) < 3 || false === $args[2] ) 
  10. $uri = $_SERVER['REQUEST_URI']; 
  11. else 
  12. $uri = $args[2]; 
  13.  
  14. if ( $frag = strstr( $uri, '#' ) ) 
  15. $uri = substr( $uri, 0, -strlen( $frag ) ); 
  16. else 
  17. $frag = ''; 
  18.  
  19. if ( 0 === stripos( $uri, 'http://' ) ) { 
  20. $protocol = 'http://'; 
  21. $uri = substr( $uri, 7 ); 
  22. } elseif ( 0 === stripos( $uri, 'https://' ) ) { 
  23. $protocol = 'https://'; 
  24. $uri = substr( $uri, 8 ); 
  25. } else { 
  26. $protocol = ''; 
  27.  
  28. if ( strpos( $uri, '?' ) !== false ) { 
  29. list( $base, $query ) = explode( '?', $uri, 2 ); 
  30. $base .= '?'; 
  31. } elseif ( $protocol || strpos( $uri, '=' ) === false ) { 
  32. $base = $uri . '?'; 
  33. $query = ''; 
  34. } else { 
  35. $base = ''; 
  36. $query = $uri; 
  37.  
  38. wp_parse_str( $query, $qs ); 
  39. $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string 
  40. if ( is_array( $args[0] ) ) { 
  41. foreach ( $args[0] as $k => $v ) { 
  42. $qs[ $k ] = $v; 
  43. } else { 
  44. $qs[ $args[0] ] = $args[1]; 
  45.  
  46. foreach ( $qs as $k => $v ) { 
  47. if ( $v === false ) 
  48. unset( $qs[$k] ); 
  49.  
  50. $ret = build_query( $qs ); 
  51. $ret = trim( $ret, '?' ); 
  52. $ret = preg_replace( '#=(&|$)#', '$1', $ret ); 
  53. $ret = $protocol . $base . $ret . $frag; 
  54. $ret = rtrim( $ret, '?' ); 
  55. return $ret;