Last updated on September 13, 2023

Remove All Query Args

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Remove all query args.

To remove all query arguments (args) from a WordPress URL, you can use the remove_query_arg() function. This function allows you to remove specific query arguments or all query arguments from a given URL. Here’s an example of how you can remove all query arguments from a WordPress URL:

function wpsnippets_remove_all_query_args() {
    if ( is_admin() || ! is_single() ) {
        return;
    }

    $url = remove_query_arg( null, wp_get_referer() );
    wp_safe_redirect( $url );
    exit;
}

add_action( 'template_redirect', 'wpsnippets_remove_all_query_args' );

This code snippet removes all query arguments when a single post is being accessed and redirects the user to the same URL without the query arguments.

Inside the wpsnippets_remove_all_query_args() function, the remove_query_arg() function is used to remove all query arguments by passing null as the first argument. The wp_get_referer() function is used to retrieve the referring URL, which contains the query arguments.

The wp_safe_redirect() function is used to perform the redirect to the modified URL without the query arguments. Finally, the exit statement is used to terminate further execution after the redirect.

By adding this WordPress code snippet, you can remove all query arguments (args) from the URL when accessing a single post, providing a cleaner URL without any additional parameters.

Last updated on September 13, 2023. Originally posted on May 19, 2023.

Leave a Reply