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: add_query_arg( 'key', 'value', 'http://example.com' ); Using an associative array: add_query_arg( array(
'key1' => 'value1',
'key2' => 'value2',
), 'http://example.com' ); 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.
1132functionadd_query_arg(...$args){1133if(is_array($args[0])){1134if(count($args)<2||false===$args[1]){1135$uri=$_SERVER['REQUEST_URI'];1136}else{1137$uri=$args[1];1138}1139}else{1140if(count($args)<3||false===$args[2]){1141$uri=$_SERVER['REQUEST_URI'];1142}else{1143$uri=$args[2];1144}1145}11461147$frag=strstr($uri,'#');1148if($frag){1149$uri=substr($uri,0,-strlen($frag));1150}else{1151$frag='';1152}11531154if(0===stripos($uri,'http://')){1155$protocol='http://';1156$uri=substr($uri,7);1157}elseif(0===stripos($uri,'https://')){1158$protocol='https://';1159$uri=substr($uri,8);1160}else{1161$protocol='';1162}11631164if(str_contains($uri,'?')){1165list($base,$query)=explode('?',$uri,2);1166$base.='?';1167}elseif($protocol||!str_contains($uri,'=')){1168$base=$uri.'?';1169$query='';1170}else{1171$base='';1172$query=$uri;1173}11741175wp_parse_str($query,$qs);1176$qs=urlencode_deep($qs);// This re-URL-encodes things that were already in the query string.1177if(is_array($args[0])){1178foreach($args[0]as$k=>$v){1179$qs[$k]=$v;1180}1181}else{1182$qs[$args[0]]=$args[1];1183}11841185foreach($qsas$k=>$v){1186if(false===$v){1187unset($qs[$k]);1188}1189}11901191$ret=build_query($qs);1192$ret=trim($ret,'?');1193$ret=preg_replace('#=(&|$)#','$1',$ret);1194$ret=$protocol.$base.$ret.$frag;1195$ret=rtrim($ret,'?');1196$ret=str_replace('?#','#',$ret);1197return$ret;1198}
History
Introduced in 1.5.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
5.3.0
Formalized the existing and already documented parameters by adding ...$args to the function signature.from the docblock
1.5.0
Introduced.from the docblock
About this page
Parsed data
Generated from the wordpress-develop 6.7.7 tag, from src/wp-includes/functions.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.