Let's say I'm using wp_localize_script
to pass base REST url to my script in a Wordpress plugin:
wp_register_script( 'my-plugin', plugin_dir_url( __FILE__ ) . '../dist/admin-main.js', [], '0.9.2' );
wp_localize_script( 'my-plugin', 'MY_PLUGIN_WP_REST_API_CONFIG', [
'baseUrl' => esc_url_raw( rest_url() ),
] );
wp_enqueue_script( 'my-plugin' );
In my JS files I need to fetch some data using query strings in my GET request, like so:
const baseUrl = MY_PLUGIN_WP_REST_API_CONFIG.baseUrl;
fetch(baseUrl + 'wp/v2/custom_post_type?per_page=100&order=asc').then(response => ...);
However, the above will only work with 'cool' permalinks, when the url resolves to something like https://example.com/wp-json/wp/v2/custom_post_type?per_page=100&order=asc
.
When not using pretty permalinks, this would translate to https://example.com/?rest_route=/wp/v2/custom_post_type?per_page=100&order=asc
, which is invalid, because there would be multiple ?
signs in the querystring, thus throwing 404 error on the request.
Is there a best practice that I'm missing where I would detect the permalink structure and construct my querystring based on some data passed from backend? The obvious solution in my case would be to parse the baseUrl
variable in javascript and add some sort of a conditional, but that seems too hacky and error prone to me.