In more recent browsers (everything but IE, essentially), there are some useful APIs for working with URLs that will make this easier:
let url = new URL( MY_PLUGIN_WP_REST_API_CONFIG.baseUrl );
url.searchParams.append( 'per_page', 100 );
url.searchParams.append( 'order', 'asc' );
fetch( url.toString() ).then();
With those methods the per_page
and order
parameters will be added correctly regardless of whether or not the original URL has a query string. But as I mentioned, these aren't available in IE, although there is a polyfill available here. You're using const
and fetch()
though, so I'm not sure this is a concern for you.
A more blunt solution that would work in any browser could be to just check if the URL contains a ?
, and if it does, use a &
character to add your parameters, otherwise use a ?
:
var baseUrl = MY_PLUGIN_WP_REST_API_CONFIG.baseUrl;
var params = 'per_page=100&order=asc'
if ( baseUrl.indexOf( '?' ) > 0-1 ) {
var url = baseUrl + '&' + params;
} else {
var url = baseUrl + '?' + params;
}
fetch( url ).then();
Libraries like axios or jQuery might also have ways to handle adding parameters to a URL that are more sophisticated than fetch
, which doesn't have functionality for adding query parameters other than including them in the URL string.