0

I am using the below code in functions.php to add custom query variables to my WordPress project.

<?php
function add_custom_query_var( $vars ){
  $vars[] = "brand";
  return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
?>

And then on the content page I am using:

<?php echo $currentbrand = get_query_var('brand'); ?>

So now I can pass a URL like:

http://myexamplesite.com/store/?brand=nike

and get nike in result.

How can I pass multiple values for a brand. So I would like to have 3 values for brand say, nike, adidas and woodland.

I have tried the following and none of them works:

  1. http://myexamplesite.com/store/?brand=nike&brand=adidas&brand=woodland It just returns the last brand, in this case woodland.

  2. http://myexamplesite.com/store/?brand=nike+adidas+woodland This returns all three with spaces. I kind of think this is not the correct solution. So may be there is a correct way to pass multiple values for a query variable and retrieve them in an array may be so that a loop can be run.

2 Answers 2

3

Usually you would pass the parameter like ?brand[]=unresponsibleCompany1&brand[]=otherBrandThatDoesNotCareMuch&brand[]=bunchOfCriminals .

In your WordPress PHP code, then get_query_var( 'brand' ) will return you an Array.

Everything else sounds like a relatively cheap but costy workaround.

Sign up to request clarification or add additional context in comments.

Comments

1

You will need to pass query parameters in this way;

brand1=nike&brand2=adidas&brand3=woodland

So, different key for each brand

On the page, recieving values

$params = $_GET;
$brands = array();
foreach($params as $k=>$v) {
    if(substr($k,0,5)=="brand") {
        $brands[] = $v;
    }
}

Alternatively

Using your 2nd method http://myexamplesite.com/store/?brand=nike+adidas+woodland

$brands = explode(" ", $_GET['brand']);

Alternative method looks easier 🙂

3 Comments

Thanks. Different key will work. But I would like to know if it is possible with just a single key.
@KiranDash updated the answer, I guess alternative method is what you looking for
I guess I will go with this. But what I was really looking for here was if WordPress has a built in solution for this. Which I guess does not exist

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.