You must use the following function to remove the sort key in an existing URL and then add.
function remove_querystring_var($url, $key) { $url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&'); $url = substr($url, 0, -1); return $url; }
Your code should change this way
<?php //get current URL $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $url = remove_querystring_var($url, "sort"); //filter URL and create sorting links if(filter_var($url, FILTER_VALIDATE_URL)) { ?> <a href="<?php echo $url; ?>?sort=asc">Small</a> <a href="<?php echo $url; ?>?sort=desc">Large</a> <?php } ?>
source share