1

The Goal

I am wanting to use add_query_arg() like so:

$url = add_query_arg(array(
    'count'    => '100',
    'property' => array(
        'abc',
        'xyz'
    )
), $base_url );

The api I am using requires me to repeat the property key in my api call

http://api-call.com/?count=100&property=abc&property=xyz 


The Problem

WordPress is outputting the code below because it is an array.

http://api-call.com/?count=100&property[0]=abc&property[1]=xyz  


I have tried this workaround:

$url = add_query_arg(array(
    'count'    => '100',
    'property' => 'abc',
    'property' => 'xyz'
), $base_url );

but WordPress outputs only the last property value

http://api-call.com/?count=100&property=xyz  


Any help is greatly appreciated!

1

You have to do a search and replace on $url like the following -

$url = add_query_arg( array(
    'count'    => '100',
    'property' => array(
        'abc',
        'xyz'
    )
), $base_url );

// following line will remove [*] and * can be nothing or 0-9
$api_url = preg_replace( '/\[\d*\]/', '', $url );

// Output will be like the following
// http://api-call.com/?count=100&property=abc&property=xyz 
| improve this answer | |
  • Hey @obiPlabon, I have 13 properties. Would this replace 10, 11, 12 with nothing? – John Fuller Feb 15 '18 at 19:21
  • It'll replace these patterns [] and [n]. Where n can be 0 to any number, e.g 10, 11, 12, 100, 200, 9999999. I said nothing or 0-9, not 10, 12 with nothing. – obiPlabon Feb 15 '18 at 19:32
  • There isn't a smarter built-in solution for this? using regex is plainly not a nice solution but rather a hack - you can use it everywhere - but should you? – trainoasis Nov 18 '19 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.