add_query_arg() One Key with multiple values

[*]

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 Answer
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 

Leave a Comment