Last Updated: September 30, 2021
·
73.34K
· michiels

Add query string params/arguments to any WordPress URL

I am creating a custom page template that lists items from a "genre" taxonomy as a kind of sub menu. When you click on a genre, I want the person to stay on the custom page, but pass the chosen genre as a parameter.

Great for making custom listings of events, photo albums, or other custom types of posts.

Picture

Turns out there is cool method for this. Especially if you use it in combination with the standard get_permalink() function:

<?php
    $genre_url = add_query_arg('genre', $term->slug, get_permalink());
    # Outputs for example: http://my_wordpress.com/photos?genre=pop
?>

This way you don't have to parse get_permalink(), see if there are already query parameters in there. You just pass in the key-value pairs of what you would like to add and you pass in the original URL as the third argument.

See http://codex.wordpress.org/Function_Reference/add_query_arg for more info.

5 Responses
Add your response

There are all sorts of weird and wonderful functions like this in the WordPress Codex, thanks for pointing this one out :)

over 1 year ago ·

and how can you delete an argument from an URL?

say, I have such an UTL:
site.com/page/3/?action=some

How to transform it into this:
site.com/?action=some or site.com/page/2/?action=some

over 1 year ago ·

I'm avare of removequeryarg() function. It does not help in this case(

over 1 year ago ·

@dimasmagadan

the removequeryarg() function only works on query parameters (so, everything behind the ?). For example, you can use removequeryarg("action", "site.com/?action=some") to get "site.com".

If you want to change or remove the "page/3" part you should really just grab the link to the correct url or permalink. Does that make sense?

over 1 year ago ·

nope, this will not work in my case.
or I can figure out hov to make it work)

what I have is:
three custom taxonomies. Let them be color, size, and region.
initial URL is site.com/somepage/
I alter this link with addqueryarg, so it becomes
site.com/somepage/?size=big

Next a user moves to page
site.com/somepage/page/3/?size=big
addqueryarg will use 'site.com/somepage/page/3/' if to skip second argument.
And the permalink still shows as 'site.com/somepage/'

What I do now is I have several checks like if(isset($_GET['size'])) ...
This seems to be a way out for a short list of terms, but what if there are 20-30 terms?
Believe there should be a way to work with URL)

over 1 year ago ·