user1548172
user1548172

Reputation:

PHP in URLs - how to add 'or' to queries (instead of x&y&z, x or y or z)?

I'm using a wordpress plugin which redirects to a random post. It allows me to redirect to random posts based on tags, so the url might look like

example.com/?random&random_tag_id=100

If I wanted to find random posts which are tagged with tag ids 100 and 101, I would just do

example.com/?random&random_tag_id=100&random_tag_id=101

But I want to find random posts which are from EITHER ids 100 or 101. I know & is used for 'this + this', but would it be possible to make a 'this OR this' request via the URL?

Thanks for any help!

Upvotes: 0

Views: 61

Answers (4)

jdp
jdp

Reputation: 3516

You're misunderstanding how GET parameters work.

In a Query String (?key=a&otherkey=b), the & is just a delimiter between the different key/var pairs. So the PHP equivalent of that string is this:

$_GET['key'] = 'a';
$_GET['otherkey'] = 'b';

If you use the same key twice in a query string, the latter will overwrite the former. So for the string ?key=a&key=b, $_GET['key'] will be equal to b.

As others have said, you can pass data via a comma separated list, (i.e. ?key=1,2,3,4), or via an array, (i.e. ?key[]=a&key[]=b).

Upvotes: 0

Machavity
Machavity

Reputation: 31624

The problem with doing it that way is you'll overwrite the value in PHP. You need bracket notation to pass it correctly as an array

example.com/?random&random_tag_id[]=100&random_tag_id[]=101

When you get to your PHP then you'll have

echo $_GET['random_tag_id'][0]; //Outputs 100

You could then pass into your query an imploded list

Upvotes: 0

vp_arth
vp_arth

Reputation: 14992

You can pass arrays to query like this:

example.com/?random&random_tag_id[]=100&random_tag_id[]=101

You'll get $_GET['random_tag_id'] == array(100, 101)

Upvotes: 0

scrowler
scrowler

Reputation: 24405

You can do something like this:

example.com/?random&random_tag_id=100,101,102,103

You'll then have to do something like this when you process those variables:

<?php
$random_tag_ids = explode(',', $_GET['random_tag_id']);
// $random_tag_ids now contains an array of your random tag ids
?>

Upvotes: 1

Related Questions