Skip to content

Instantly share code, notes, and snippets.

@mohdsayed
Last active January 24, 2020 04:15
Show Gist options
  • Save mohdsayed/365dfbc057f133696ec74490644fa9a2 to your computer and use it in GitHub Desktop.
Save mohdsayed/365dfbc057f133696ec74490644fa9a2 to your computer and use it in GitHub Desktop.
Fetch request for REST API
// Exported from php.
const exports = {
restBase: {
url: 'https://example.org/wp-json/wp/v2',
nonce: '3433DFE2',
}
};
// Utils function.
const getRestUrl = ( endpoint, params ) => {
const url = `${ exports.restBase.url }/${ endpoint }?_wpnonce=${ exports.restBase.nonce }`;
return Object.keys( params ).reduce( ( accum, key ) => accum + `&${ key }=${ params[ key ] }`, url );
};
const restUrl = getRestUrl( 'end-point', {
term_id: 23,
posts_per_page: 15,
} );
fetch( restUrl, { headers: { 'X-WP-Nonce': exports.restBase.nonce },
} ).then( response => response.json() ).then( resp => {
// Render JS template and append to DOM using resp.
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment