$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>plugins - Detect permalinks when passing querystring in REST API requests|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

plugins - Detect permalinks when passing querystring in REST API requests

matteradmin8PV0评论

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 ;order=asc.

When not using pretty permalinks, this would translate to /?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.

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/wp-json/wp/v2/custom_post_type?per_page=100&order=asc.

When not using pretty permalinks, this would translate to https://example/?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.

Share Improve this question asked Mar 8, 2019 at 14:19 Filip RůžičkaFilip Růžička 1134 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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( '?' ) > -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.

Post a comment

comment list (0)

  1. No comments so far