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.
1138functionadd_query_arg(...$args){1139if(is_array($args[0])){1140if(count($args)<2||false===$args[1]){1141$uri=$_SERVER['REQUEST_URI'];1142}else{1143$uri=$args[1];1144}1145}else{1146if(count($args)<3||false===$args[2]){1147$uri=$_SERVER['REQUEST_URI'];1148}else{1149$uri=$args[2];1150}1151}11521153$frag=strstr($uri,'#');1154if($frag){1155$uri=substr($uri,0,-strlen($frag));1156}else{1157$frag='';1158}11591160if(0===stripos($uri,'http://')){1161$protocol='http://';1162$uri=substr($uri,7);1163}elseif(0===stripos($uri,'https://')){1164$protocol='https://';1165$uri=substr($uri,8);1166}else{1167$protocol='';1168}11691170if(str_contains($uri,'?')){1171list($base,$query)=explode('?',$uri,2);1172$base.='?';1173}elseif($protocol||!str_contains($uri,'=')){1174$base=$uri.'?';1175$query='';1176}else{1177$base='';1178$query=$uri;1179}11801181wp_parse_str($query,$qs);1182$qs=urlencode_deep($qs);// This re-URL-encodes things that were already in the query string.1183if(is_array($args[0])){1184foreach($args[0]as$k=>$v){1185$qs[$k]=$v;1186}1187}else{1188$qs[$args[0]]=$args[1];1189}11901191foreach($qsas$k=>$v){1192if(false===$v){1193unset($qs[$k]);1194}1195}11961197$ret=build_query($qs);1198$ret=trim($ret,'?');1199$ret=preg_replace('#=(&|$)#','$1',$ret);1200$ret=$protocol.$base.$ret.$frag;1201$ret=rtrim($ret,'?');1202$ret=str_replace('?#','#',$ret);1203return$ret;1204}
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.8.8 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.