WordPress – How to remove all query args from a URL

The following code shows how to remove all but one query args from a URL.

This code has been written for WordPress, but if used outside of WordPress you’ll just need to find an alternative for add_query_arg().

It assumes that you have the URL as a string – which is not nesecarily the same as the URL for the current WordPress install that’s running the code.

For example, if you had the URL

http://demo.itsupportguides.com/?token=12345&p=1&p=2

and wanted to remove all query args except for token, it will return

http://demo.itsupportguides.com/?token=12345

If token doesn’t exist, it will return

Home

$url = 'http://demo.itsupportguides.com/?token=12345&p=1&p=2';

$url_parts = parse_url( $url );

parse_str( $url_parts['query'], $query_parameters );

$token = isset( $query_parameters['token'] ) ? $query_parameters['token'] : '';

$new_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];

if ( ! empty( $token ) ) {
    $new_url = add_query_arg( array( 'token' => $token ), $new_url );
}